api-web-contents-spec.ts 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500
  1. import { expect } from 'chai';
  2. import { AddressInfo } from 'node:net';
  3. import * as path from 'node:path';
  4. import * as fs from 'node:fs';
  5. import * as http from 'node:http';
  6. import { BrowserWindow, ipcMain, webContents, session, app, BrowserView, WebContents } from 'electron/main';
  7. import { closeAllWindows } from './lib/window-helpers';
  8. import { ifdescribe, defer, waitUntil, listen, ifit } from './lib/spec-helpers';
  9. import { once } from 'node:events';
  10. import { setTimeout } from 'node:timers/promises';
  11. const pdfjs = require('pdfjs-dist');
  12. const fixturesPath = path.resolve(__dirname, 'fixtures');
  13. const mainFixturesPath = path.resolve(__dirname, 'fixtures');
  14. const features = process._linkedBinding('electron_common_features');
  15. describe('webContents module', () => {
  16. describe('getAllWebContents() API', () => {
  17. afterEach(closeAllWindows);
  18. it('returns an array of web contents', async () => {
  19. const w = new BrowserWindow({
  20. show: false,
  21. webPreferences: { webviewTag: true }
  22. });
  23. w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html'));
  24. await once(w.webContents, 'did-attach-webview') as [any, WebContents];
  25. w.webContents.openDevTools();
  26. await once(w.webContents, 'devtools-opened');
  27. const all = webContents.getAllWebContents().sort((a, b) => {
  28. return a.id - b.id;
  29. });
  30. expect(all).to.have.length(3);
  31. expect(all[0].getType()).to.equal('window');
  32. expect(all[all.length - 2].getType()).to.equal('webview');
  33. expect(all[all.length - 1].getType()).to.equal('remote');
  34. });
  35. });
  36. describe('fromId()', () => {
  37. it('returns undefined for an unknown id', () => {
  38. expect(webContents.fromId(12345)).to.be.undefined();
  39. });
  40. });
  41. describe('fromFrame()', () => {
  42. it('returns WebContents for mainFrame', () => {
  43. const contents = (webContents as typeof ElectronInternal.WebContents).create();
  44. expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents);
  45. });
  46. it('returns undefined for disposed frame', async () => {
  47. const contents = (webContents as typeof ElectronInternal.WebContents).create();
  48. const { mainFrame } = contents;
  49. contents.destroy();
  50. await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined');
  51. });
  52. it('throws when passing invalid argument', async () => {
  53. let errored = false;
  54. try {
  55. webContents.fromFrame({} as any);
  56. } catch {
  57. errored = true;
  58. }
  59. expect(errored).to.be.true();
  60. });
  61. });
  62. describe('fromDevToolsTargetId()', () => {
  63. it('returns WebContents for attached DevTools target', async () => {
  64. const w = new BrowserWindow({ show: false });
  65. await w.loadURL('about:blank');
  66. try {
  67. await w.webContents.debugger.attach('1.3');
  68. const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo');
  69. expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents);
  70. } finally {
  71. await w.webContents.debugger.detach();
  72. }
  73. });
  74. it('returns undefined for an unknown id', () => {
  75. expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined();
  76. });
  77. });
  78. describe('will-prevent-unload event', function () {
  79. afterEach(closeAllWindows);
  80. it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => {
  81. const w = new BrowserWindow({ show: false });
  82. w.webContents.once('will-prevent-unload', () => {
  83. expect.fail('should not have fired');
  84. });
  85. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
  86. const wait = once(w, 'closed');
  87. w.close();
  88. await wait;
  89. });
  90. it('does not emit if beforeunload returns undefined in a BrowserView', async () => {
  91. const w = new BrowserWindow({ show: false });
  92. const view = new BrowserView();
  93. w.setBrowserView(view);
  94. view.setBounds(w.getBounds());
  95. view.webContents.once('will-prevent-unload', () => {
  96. expect.fail('should not have fired');
  97. });
  98. await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
  99. const wait = once(w, 'closed');
  100. w.close();
  101. await wait;
  102. });
  103. it('emits if beforeunload returns false in a BrowserWindow', async () => {
  104. const w = new BrowserWindow({ show: false });
  105. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  106. w.close();
  107. await once(w.webContents, 'will-prevent-unload');
  108. });
  109. it('emits if beforeunload returns false in a BrowserView', async () => {
  110. const w = new BrowserWindow({ show: false });
  111. const view = new BrowserView();
  112. w.setBrowserView(view);
  113. view.setBounds(w.getBounds());
  114. await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  115. w.close();
  116. await once(view.webContents, 'will-prevent-unload');
  117. });
  118. it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => {
  119. const w = new BrowserWindow({ show: false });
  120. w.webContents.once('will-prevent-unload', event => event.preventDefault());
  121. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  122. const wait = once(w, 'closed');
  123. w.close();
  124. await wait;
  125. });
  126. });
  127. describe('webContents.send(channel, args...)', () => {
  128. afterEach(closeAllWindows);
  129. it('throws an error when the channel is missing', () => {
  130. const w = new BrowserWindow({ show: false });
  131. expect(() => {
  132. (w.webContents.send as any)();
  133. }).to.throw('Missing required channel argument');
  134. expect(() => {
  135. w.webContents.send(null as any);
  136. }).to.throw('Missing required channel argument');
  137. });
  138. it('does not block node async APIs when sent before document is ready', (done) => {
  139. // Please reference https://github.com/electron/electron/issues/19368 if
  140. // this test fails.
  141. ipcMain.once('async-node-api-done', () => {
  142. done();
  143. });
  144. const w = new BrowserWindow({
  145. show: false,
  146. webPreferences: {
  147. nodeIntegration: true,
  148. sandbox: false,
  149. contextIsolation: false
  150. }
  151. });
  152. w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html'));
  153. setTimeout(50).then(() => {
  154. w.webContents.send('test');
  155. });
  156. });
  157. });
  158. ifdescribe(features.isPrintingEnabled())('webContents.print()', () => {
  159. let w: BrowserWindow;
  160. beforeEach(() => {
  161. w = new BrowserWindow({ show: false });
  162. });
  163. afterEach(closeAllWindows);
  164. it('throws when invalid settings are passed', () => {
  165. expect(() => {
  166. // @ts-ignore this line is intentionally incorrect
  167. w.webContents.print(true);
  168. }).to.throw('webContents.print(): Invalid print settings specified.');
  169. });
  170. it('throws when an invalid pageSize is passed', () => {
  171. const badSize = 5;
  172. expect(() => {
  173. // @ts-ignore this line is intentionally incorrect
  174. w.webContents.print({ pageSize: badSize });
  175. }).to.throw(`Unsupported pageSize: ${badSize}`);
  176. });
  177. it('throws when an invalid callback is passed', () => {
  178. expect(() => {
  179. // @ts-ignore this line is intentionally incorrect
  180. w.webContents.print({}, true);
  181. }).to.throw('webContents.print(): Invalid optional callback provided.');
  182. });
  183. it('fails when an invalid deviceName is passed', (done) => {
  184. w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => {
  185. expect(success).to.equal(false);
  186. expect(reason).to.match(/Invalid deviceName provided/);
  187. done();
  188. });
  189. });
  190. it('throws when an invalid pageSize is passed', () => {
  191. expect(() => {
  192. // @ts-ignore this line is intentionally incorrect
  193. w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {});
  194. }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize');
  195. });
  196. it('throws when an invalid custom pageSize is passed', () => {
  197. expect(() => {
  198. w.webContents.print({
  199. pageSize: {
  200. width: 100,
  201. height: 200
  202. }
  203. });
  204. }).to.throw('height and width properties must be minimum 352 microns.');
  205. });
  206. it('does not crash with custom margins', () => {
  207. expect(() => {
  208. w.webContents.print({
  209. silent: true,
  210. margins: {
  211. marginType: 'custom',
  212. top: 1,
  213. bottom: 1,
  214. left: 1,
  215. right: 1
  216. }
  217. });
  218. }).to.not.throw();
  219. });
  220. });
  221. describe('webContents.executeJavaScript', () => {
  222. describe('in about:blank', () => {
  223. const expected = 'hello, world!';
  224. const expectedErrorMsg = 'woops!';
  225. const code = `(() => "${expected}")()`;
  226. const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`;
  227. const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`;
  228. const errorTypes = new Set([
  229. Error,
  230. ReferenceError,
  231. EvalError,
  232. RangeError,
  233. SyntaxError,
  234. TypeError,
  235. URIError
  236. ]);
  237. let w: BrowserWindow;
  238. before(async () => {
  239. w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } });
  240. await w.loadURL('about:blank');
  241. });
  242. after(closeAllWindows);
  243. it('resolves the returned promise with the result', async () => {
  244. const result = await w.webContents.executeJavaScript(code);
  245. expect(result).to.equal(expected);
  246. });
  247. it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => {
  248. const result = await w.webContents.executeJavaScript(asyncCode);
  249. expect(result).to.equal(expected);
  250. });
  251. it('rejects the returned promise if an async error is thrown', async () => {
  252. await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg);
  253. });
  254. it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
  255. for (const error of errorTypes) {
  256. await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`))
  257. .to.eventually.be.rejectedWith(error);
  258. }
  259. });
  260. });
  261. describe('on a real page', () => {
  262. let w: BrowserWindow;
  263. beforeEach(() => {
  264. w = new BrowserWindow({ show: false });
  265. });
  266. afterEach(closeAllWindows);
  267. let server: http.Server;
  268. let serverUrl: string;
  269. before(async () => {
  270. server = http.createServer((request, response) => {
  271. response.end();
  272. });
  273. serverUrl = (await listen(server)).url;
  274. });
  275. after(() => {
  276. server.close();
  277. });
  278. it('works after page load and during subframe load', async () => {
  279. await w.loadURL(serverUrl);
  280. // initiate a sub-frame load, then try and execute script during it
  281. await w.webContents.executeJavaScript(`
  282. var iframe = document.createElement('iframe')
  283. iframe.src = '${serverUrl}/slow'
  284. document.body.appendChild(iframe)
  285. null // don't return the iframe
  286. `);
  287. await w.webContents.executeJavaScript('console.log(\'hello\')');
  288. });
  289. it('executes after page load', async () => {
  290. const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()');
  291. w.loadURL(serverUrl);
  292. const result = await executeJavaScript;
  293. expect(result).to.equal('test');
  294. });
  295. });
  296. });
  297. describe('webContents.executeJavaScriptInIsolatedWorld', () => {
  298. let w: BrowserWindow;
  299. before(async () => {
  300. w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } });
  301. await w.loadURL('about:blank');
  302. });
  303. it('resolves the returned promise with the result', async () => {
  304. await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]);
  305. const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]);
  306. const mainWorldResult = await w.webContents.executeJavaScript('window.X');
  307. expect(isolatedResult).to.equal(123);
  308. expect(mainWorldResult).to.equal(undefined);
  309. });
  310. });
  311. describe('loadURL() promise API', () => {
  312. let w: BrowserWindow;
  313. beforeEach(async () => {
  314. w = new BrowserWindow({ show: false });
  315. });
  316. afterEach(closeAllWindows);
  317. it('resolves when done loading', async () => {
  318. await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
  319. });
  320. it('resolves when done loading a file URL', async () => {
  321. await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled();
  322. });
  323. it('resolves when navigating within the page', async () => {
  324. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  325. await setTimeout();
  326. await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled();
  327. });
  328. it('resolves after browser initiated navigation', async () => {
  329. let finishedLoading = false;
  330. w.webContents.on('did-finish-load', function () {
  331. finishedLoading = true;
  332. });
  333. await w.loadFile(path.join(fixturesPath, 'pages', 'navigate_in_page_and_wait.html'));
  334. expect(finishedLoading).to.be.true();
  335. });
  336. it('rejects when failing to load a file URL', async () => {
  337. await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected()
  338. .and.have.property('code', 'ERR_FILE_NOT_FOUND');
  339. });
  340. // FIXME: Temporarily disable on WOA until
  341. // https://github.com/electron/electron/issues/20008 is resolved
  342. ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('rejects when loading fails due to DNS not resolved', async () => {
  343. await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected()
  344. .and.have.property('code', 'ERR_NAME_NOT_RESOLVED');
  345. });
  346. it('rejects when navigation is cancelled due to a bad scheme', async () => {
  347. await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected()
  348. .and.have.property('code', 'ERR_FAILED');
  349. });
  350. it('does not crash when loading a new URL with emulation settings set', async () => {
  351. const setEmulation = async () => {
  352. if (w.webContents) {
  353. w.webContents.debugger.attach('1.3');
  354. const deviceMetrics = {
  355. width: 700,
  356. height: 600,
  357. deviceScaleFactor: 2,
  358. mobile: true,
  359. dontSetVisibleSize: true
  360. };
  361. await w.webContents.debugger.sendCommand(
  362. 'Emulation.setDeviceMetricsOverride',
  363. deviceMetrics
  364. );
  365. }
  366. };
  367. try {
  368. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  369. await setEmulation();
  370. await w.loadURL('data:text/html,<h1>HELLO</h1>');
  371. await setEmulation();
  372. } catch (e) {
  373. expect((e as Error).message).to.match(/Debugger is already attached to the target/);
  374. }
  375. });
  376. it('sets appropriate error information on rejection', async () => {
  377. let err: any;
  378. try {
  379. await w.loadURL('file:non-existent');
  380. } catch (e) {
  381. err = e;
  382. }
  383. expect(err).not.to.be.null();
  384. expect(err.code).to.eql('ERR_FILE_NOT_FOUND');
  385. expect(err.errno).to.eql(-6);
  386. expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent');
  387. });
  388. it('rejects if the load is aborted', async () => {
  389. const s = http.createServer(() => { /* never complete the request */ });
  390. const { port } = await listen(s);
  391. const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/);
  392. // load a different file before the first load completes, causing the
  393. // first load to be aborted.
  394. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  395. await p;
  396. s.close();
  397. });
  398. it("doesn't reject when a subframe fails to load", async () => {
  399. let resp = null as unknown as http.ServerResponse;
  400. const s = http.createServer((req, res) => {
  401. res.writeHead(200, { 'Content-Type': 'text/html' });
  402. res.write('<iframe src="http://err.name.not.resolved"></iframe>');
  403. resp = res;
  404. // don't end the response yet
  405. });
  406. const { port } = await listen(s);
  407. const p = new Promise<void>(resolve => {
  408. w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => {
  409. if (!isMainFrame) {
  410. resolve();
  411. }
  412. });
  413. });
  414. const main = w.loadURL(`http://127.0.0.1:${port}`);
  415. await p;
  416. resp.end();
  417. await main;
  418. s.close();
  419. });
  420. it("doesn't resolve when a subframe loads", async () => {
  421. let resp = null as unknown as http.ServerResponse;
  422. const s = http.createServer((req, res) => {
  423. res.writeHead(200, { 'Content-Type': 'text/html' });
  424. res.write('<iframe src="about:blank"></iframe>');
  425. resp = res;
  426. // don't end the response yet
  427. });
  428. const { port } = await listen(s);
  429. const p = new Promise<void>(resolve => {
  430. w.webContents.on('did-frame-finish-load', (event, isMainFrame) => {
  431. if (!isMainFrame) {
  432. resolve();
  433. }
  434. });
  435. });
  436. const main = w.loadURL(`http://127.0.0.1:${port}`);
  437. await p;
  438. resp.destroy(); // cause the main request to fail
  439. await expect(main).to.eventually.be.rejected()
  440. .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING
  441. s.close();
  442. });
  443. });
  444. describe('getFocusedWebContents() API', () => {
  445. afterEach(closeAllWindows);
  446. // FIXME
  447. ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('returns the focused web contents', async () => {
  448. const w = new BrowserWindow({ show: true });
  449. await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  450. expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
  451. const devToolsOpened = once(w.webContents, 'devtools-opened');
  452. w.webContents.openDevTools();
  453. await devToolsOpened;
  454. expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.devToolsWebContents!.id);
  455. const devToolsClosed = once(w.webContents, 'devtools-closed');
  456. w.webContents.closeDevTools();
  457. await devToolsClosed;
  458. expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
  459. });
  460. it('does not crash when called on a detached dev tools window', async () => {
  461. const w = new BrowserWindow({ show: true });
  462. w.webContents.openDevTools({ mode: 'detach' });
  463. w.webContents.inspectElement(100, 100);
  464. // For some reason we have to wait for two focused events...?
  465. await once(w.webContents, 'devtools-focused');
  466. expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
  467. // Work around https://github.com/electron/electron/issues/19985
  468. await setTimeout();
  469. const devToolsClosed = once(w.webContents, 'devtools-closed');
  470. w.webContents.closeDevTools();
  471. await devToolsClosed;
  472. expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
  473. });
  474. });
  475. describe('setDevToolsWebContents() API', () => {
  476. afterEach(closeAllWindows);
  477. it('sets arbitrary webContents as devtools', async () => {
  478. const w = new BrowserWindow({ show: false });
  479. const devtools = new BrowserWindow({ show: false });
  480. const promise = once(devtools.webContents, 'dom-ready');
  481. w.webContents.setDevToolsWebContents(devtools.webContents);
  482. w.webContents.openDevTools();
  483. await promise;
  484. expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true();
  485. const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name');
  486. expect(result).to.equal('InspectorFrontendHostImpl');
  487. devtools.destroy();
  488. });
  489. });
  490. describe('isFocused() API', () => {
  491. it('returns false when the window is hidden', async () => {
  492. const w = new BrowserWindow({ show: false });
  493. await w.loadURL('about:blank');
  494. expect(w.isVisible()).to.be.false();
  495. expect(w.webContents.isFocused()).to.be.false();
  496. });
  497. });
  498. describe('isCurrentlyAudible() API', () => {
  499. afterEach(closeAllWindows);
  500. it('returns whether audio is playing', async () => {
  501. const w = new BrowserWindow({ show: false });
  502. await w.loadURL('about:blank');
  503. await w.webContents.executeJavaScript(`
  504. window.context = new AudioContext
  505. // Start in suspended state, because of the
  506. // new web audio api policy.
  507. context.suspend()
  508. window.oscillator = context.createOscillator()
  509. oscillator.connect(context.destination)
  510. oscillator.start()
  511. `);
  512. let p = once(w.webContents, 'audio-state-changed');
  513. w.webContents.executeJavaScript('context.resume()');
  514. await p;
  515. expect(w.webContents.isCurrentlyAudible()).to.be.true();
  516. p = once(w.webContents, 'audio-state-changed');
  517. w.webContents.executeJavaScript('oscillator.stop()');
  518. await p;
  519. expect(w.webContents.isCurrentlyAudible()).to.be.false();
  520. });
  521. });
  522. describe('openDevTools() API', () => {
  523. afterEach(closeAllWindows);
  524. it('can show window with activation', async () => {
  525. const w = new BrowserWindow({ show: false });
  526. const focused = once(w, 'focus');
  527. w.show();
  528. await focused;
  529. expect(w.isFocused()).to.be.true();
  530. const blurred = once(w, 'blur');
  531. w.webContents.openDevTools({ mode: 'detach', activate: true });
  532. await Promise.all([
  533. once(w.webContents, 'devtools-opened'),
  534. once(w.webContents, 'devtools-focused')
  535. ]);
  536. await blurred;
  537. expect(w.isFocused()).to.be.false();
  538. });
  539. it('can show window without activation', async () => {
  540. const w = new BrowserWindow({ show: false });
  541. const devtoolsOpened = once(w.webContents, 'devtools-opened');
  542. w.webContents.openDevTools({ mode: 'detach', activate: false });
  543. await devtoolsOpened;
  544. expect(w.webContents.isDevToolsOpened()).to.be.true();
  545. });
  546. it('can show a DevTools window with custom title', async () => {
  547. const w = new BrowserWindow({ show: false });
  548. const devtoolsOpened = once(w.webContents, 'devtools-opened');
  549. w.webContents.openDevTools({ mode: 'detach', activate: false, title: 'myTitle' });
  550. await devtoolsOpened;
  551. expect(w.webContents.getDevToolsTitle()).to.equal('myTitle');
  552. });
  553. });
  554. describe('setDevToolsTitle() API', () => {
  555. afterEach(closeAllWindows);
  556. it('can set devtools title with function', async () => {
  557. const w = new BrowserWindow({ show: false });
  558. const devtoolsOpened = once(w.webContents, 'devtools-opened');
  559. w.webContents.openDevTools({ mode: 'detach', activate: false });
  560. await devtoolsOpened;
  561. expect(w.webContents.isDevToolsOpened()).to.be.true();
  562. w.webContents.setDevToolsTitle('newTitle');
  563. expect(w.webContents.getDevToolsTitle()).to.equal('newTitle');
  564. });
  565. });
  566. describe('before-input-event event', () => {
  567. afterEach(closeAllWindows);
  568. it('can prevent document keyboard events', async () => {
  569. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  570. await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
  571. const keyDown = new Promise(resolve => {
  572. ipcMain.once('keydown', (event, key) => resolve(key));
  573. });
  574. w.webContents.once('before-input-event', (event, input) => {
  575. if (input.key === 'a') event.preventDefault();
  576. });
  577. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' });
  578. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' });
  579. expect(await keyDown).to.equal('b');
  580. });
  581. it('has the correct properties', async () => {
  582. const w = new BrowserWindow({ show: false });
  583. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  584. const testBeforeInput = async (opts: any) => {
  585. const modifiers = [];
  586. if (opts.shift) modifiers.push('shift');
  587. if (opts.control) modifiers.push('control');
  588. if (opts.alt) modifiers.push('alt');
  589. if (opts.meta) modifiers.push('meta');
  590. if (opts.isAutoRepeat) modifiers.push('isAutoRepeat');
  591. const p = once(w.webContents, 'before-input-event') as Promise<[any, Electron.Input]>;
  592. w.webContents.sendInputEvent({
  593. type: opts.type,
  594. keyCode: opts.keyCode,
  595. modifiers: modifiers as any
  596. });
  597. const [, input] = await p;
  598. expect(input.type).to.equal(opts.type);
  599. expect(input.key).to.equal(opts.key);
  600. expect(input.code).to.equal(opts.code);
  601. expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat);
  602. expect(input.shift).to.equal(opts.shift);
  603. expect(input.control).to.equal(opts.control);
  604. expect(input.alt).to.equal(opts.alt);
  605. expect(input.meta).to.equal(opts.meta);
  606. };
  607. await testBeforeInput({
  608. type: 'keyDown',
  609. key: 'A',
  610. code: 'KeyA',
  611. keyCode: 'a',
  612. shift: true,
  613. control: true,
  614. alt: true,
  615. meta: true,
  616. isAutoRepeat: true
  617. });
  618. await testBeforeInput({
  619. type: 'keyUp',
  620. key: '.',
  621. code: 'Period',
  622. keyCode: '.',
  623. shift: false,
  624. control: true,
  625. alt: true,
  626. meta: false,
  627. isAutoRepeat: false
  628. });
  629. await testBeforeInput({
  630. type: 'keyUp',
  631. key: '!',
  632. code: 'Digit1',
  633. keyCode: '1',
  634. shift: true,
  635. control: false,
  636. alt: false,
  637. meta: true,
  638. isAutoRepeat: false
  639. });
  640. await testBeforeInput({
  641. type: 'keyUp',
  642. key: 'Tab',
  643. code: 'Tab',
  644. keyCode: 'Tab',
  645. shift: false,
  646. control: true,
  647. alt: false,
  648. meta: false,
  649. isAutoRepeat: true
  650. });
  651. });
  652. });
  653. // On Mac, zooming isn't done with the mouse wheel.
  654. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => {
  655. afterEach(closeAllWindows);
  656. it('is emitted with the correct zoom-in info', async () => {
  657. const w = new BrowserWindow({ show: false });
  658. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  659. const testZoomChanged = async () => {
  660. w.webContents.sendInputEvent({
  661. type: 'mouseWheel',
  662. x: 300,
  663. y: 300,
  664. deltaX: 0,
  665. deltaY: 1,
  666. wheelTicksX: 0,
  667. wheelTicksY: 1,
  668. modifiers: ['control', 'meta']
  669. });
  670. const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string];
  671. expect(zoomDirection).to.equal('in');
  672. };
  673. await testZoomChanged();
  674. });
  675. it('is emitted with the correct zoom-out info', async () => {
  676. const w = new BrowserWindow({ show: false });
  677. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  678. const testZoomChanged = async () => {
  679. w.webContents.sendInputEvent({
  680. type: 'mouseWheel',
  681. x: 300,
  682. y: 300,
  683. deltaX: 0,
  684. deltaY: -1,
  685. wheelTicksX: 0,
  686. wheelTicksY: -1,
  687. modifiers: ['control', 'meta']
  688. });
  689. const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string];
  690. expect(zoomDirection).to.equal('out');
  691. };
  692. await testZoomChanged();
  693. });
  694. });
  695. describe('sendInputEvent(event)', () => {
  696. let w: BrowserWindow;
  697. beforeEach(async () => {
  698. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  699. await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
  700. });
  701. afterEach(closeAllWindows);
  702. it('can send keydown events', async () => {
  703. const keydown = once(ipcMain, 'keydown');
  704. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
  705. const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
  706. expect(key).to.equal('a');
  707. expect(code).to.equal('KeyA');
  708. expect(keyCode).to.equal(65);
  709. expect(shiftKey).to.be.false();
  710. expect(ctrlKey).to.be.false();
  711. expect(altKey).to.be.false();
  712. });
  713. it('can send keydown events with modifiers', async () => {
  714. const keydown = once(ipcMain, 'keydown');
  715. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
  716. const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
  717. expect(key).to.equal('Z');
  718. expect(code).to.equal('KeyZ');
  719. expect(keyCode).to.equal(90);
  720. expect(shiftKey).to.be.true();
  721. expect(ctrlKey).to.be.true();
  722. expect(altKey).to.be.false();
  723. });
  724. it('can send keydown events with special keys', async () => {
  725. const keydown = once(ipcMain, 'keydown');
  726. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] });
  727. const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
  728. expect(key).to.equal('Tab');
  729. expect(code).to.equal('Tab');
  730. expect(keyCode).to.equal(9);
  731. expect(shiftKey).to.be.false();
  732. expect(ctrlKey).to.be.false();
  733. expect(altKey).to.be.true();
  734. });
  735. it('can send char events', async () => {
  736. const keypress = once(ipcMain, 'keypress');
  737. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
  738. w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' });
  739. const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
  740. expect(key).to.equal('a');
  741. expect(code).to.equal('KeyA');
  742. expect(keyCode).to.equal(65);
  743. expect(shiftKey).to.be.false();
  744. expect(ctrlKey).to.be.false();
  745. expect(altKey).to.be.false();
  746. });
  747. it('can correctly convert accelerators to key codes', async () => {
  748. const keyup = once(ipcMain, 'keyup');
  749. w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' });
  750. w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' });
  751. w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' });
  752. w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' });
  753. w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' });
  754. w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'keyUp' });
  755. await keyup;
  756. const inputText = await w.webContents.executeJavaScript('document.getElementById("input").value');
  757. expect(inputText).to.equal('+ + +');
  758. });
  759. it('can send char events with modifiers', async () => {
  760. const keypress = once(ipcMain, 'keypress');
  761. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' });
  762. w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
  763. const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
  764. expect(key).to.equal('Z');
  765. expect(code).to.equal('KeyZ');
  766. expect(keyCode).to.equal(90);
  767. expect(shiftKey).to.be.true();
  768. expect(ctrlKey).to.be.true();
  769. expect(altKey).to.be.false();
  770. });
  771. });
  772. describe('insertCSS', () => {
  773. afterEach(closeAllWindows);
  774. it('supports inserting CSS', async () => {
  775. const w = new BrowserWindow({ show: false });
  776. w.loadURL('about:blank');
  777. await w.webContents.insertCSS('body { background-repeat: round; }');
  778. const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
  779. expect(result).to.equal('round');
  780. });
  781. it('supports removing inserted CSS', async () => {
  782. const w = new BrowserWindow({ show: false });
  783. w.loadURL('about:blank');
  784. const key = await w.webContents.insertCSS('body { background-repeat: round; }');
  785. await w.webContents.removeInsertedCSS(key);
  786. const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
  787. expect(result).to.equal('repeat');
  788. });
  789. });
  790. describe('inspectElement()', () => {
  791. afterEach(closeAllWindows);
  792. it('supports inspecting an element in the devtools', async () => {
  793. const w = new BrowserWindow({ show: false });
  794. w.loadURL('about:blank');
  795. const event = once(w.webContents, 'devtools-opened');
  796. w.webContents.inspectElement(10, 10);
  797. await event;
  798. });
  799. });
  800. describe('startDrag({file, icon})', () => {
  801. it('throws errors for a missing file or a missing/empty icon', () => {
  802. const w = new BrowserWindow({ show: false });
  803. expect(() => {
  804. w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any);
  805. }).to.throw('Must specify either \'file\' or \'files\' option');
  806. expect(() => {
  807. w.webContents.startDrag({ file: __filename } as any);
  808. }).to.throw('\'icon\' parameter is required');
  809. expect(() => {
  810. w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') });
  811. }).to.throw(/Failed to load image from path (.+)/);
  812. });
  813. });
  814. describe('focus APIs', () => {
  815. describe('focus()', () => {
  816. afterEach(closeAllWindows);
  817. it('does not blur the focused window when the web contents is hidden', async () => {
  818. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  819. w.show();
  820. await w.loadURL('about:blank');
  821. w.focus();
  822. const child = new BrowserWindow({ show: false });
  823. child.loadURL('about:blank');
  824. child.webContents.focus();
  825. const currentFocused = w.isFocused();
  826. const childFocused = child.isFocused();
  827. child.close();
  828. expect(currentFocused).to.be.true();
  829. expect(childFocused).to.be.false();
  830. });
  831. });
  832. const moveFocusToDevTools = async (win: BrowserWindow) => {
  833. const devToolsOpened = once(win.webContents, 'devtools-opened');
  834. win.webContents.openDevTools({ mode: 'right' });
  835. await devToolsOpened;
  836. win.webContents.devToolsWebContents!.focus();
  837. };
  838. describe('focus event', () => {
  839. afterEach(closeAllWindows);
  840. it('is triggered when web contents is focused', async () => {
  841. const w = new BrowserWindow({ show: false });
  842. await w.loadURL('about:blank');
  843. await moveFocusToDevTools(w);
  844. const focusPromise = once(w.webContents, 'focus');
  845. w.webContents.focus();
  846. await expect(focusPromise).to.eventually.be.fulfilled();
  847. });
  848. });
  849. describe('blur event', () => {
  850. afterEach(closeAllWindows);
  851. it('is triggered when web contents is blurred', async () => {
  852. const w = new BrowserWindow({ show: true });
  853. await w.loadURL('about:blank');
  854. w.webContents.focus();
  855. const blurPromise = once(w.webContents, 'blur');
  856. await moveFocusToDevTools(w);
  857. await expect(blurPromise).to.eventually.be.fulfilled();
  858. });
  859. });
  860. });
  861. describe('getOSProcessId()', () => {
  862. afterEach(closeAllWindows);
  863. it('returns a valid process id', async () => {
  864. const w = new BrowserWindow({ show: false });
  865. expect(w.webContents.getOSProcessId()).to.equal(0);
  866. await w.loadURL('about:blank');
  867. expect(w.webContents.getOSProcessId()).to.be.above(0);
  868. });
  869. });
  870. describe('getMediaSourceId()', () => {
  871. afterEach(closeAllWindows);
  872. it('returns a valid stream id', () => {
  873. const w = new BrowserWindow({ show: false });
  874. expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty();
  875. });
  876. });
  877. describe('userAgent APIs', () => {
  878. it('is not empty by default', () => {
  879. const w = new BrowserWindow({ show: false });
  880. const userAgent = w.webContents.getUserAgent();
  881. expect(userAgent).to.be.a('string').that.is.not.empty();
  882. });
  883. it('can set the user agent (functions)', () => {
  884. const w = new BrowserWindow({ show: false });
  885. const userAgent = w.webContents.getUserAgent();
  886. w.webContents.setUserAgent('my-user-agent');
  887. expect(w.webContents.getUserAgent()).to.equal('my-user-agent');
  888. w.webContents.setUserAgent(userAgent);
  889. expect(w.webContents.getUserAgent()).to.equal(userAgent);
  890. });
  891. it('can set the user agent (properties)', () => {
  892. const w = new BrowserWindow({ show: false });
  893. const userAgent = w.webContents.userAgent;
  894. w.webContents.userAgent = 'my-user-agent';
  895. expect(w.webContents.userAgent).to.equal('my-user-agent');
  896. w.webContents.userAgent = userAgent;
  897. expect(w.webContents.userAgent).to.equal(userAgent);
  898. });
  899. });
  900. describe('audioMuted APIs', () => {
  901. it('can set the audio mute level (functions)', () => {
  902. const w = new BrowserWindow({ show: false });
  903. w.webContents.setAudioMuted(true);
  904. expect(w.webContents.isAudioMuted()).to.be.true();
  905. w.webContents.setAudioMuted(false);
  906. expect(w.webContents.isAudioMuted()).to.be.false();
  907. });
  908. it('can set the audio mute level (functions)', () => {
  909. const w = new BrowserWindow({ show: false });
  910. w.webContents.audioMuted = true;
  911. expect(w.webContents.audioMuted).to.be.true();
  912. w.webContents.audioMuted = false;
  913. expect(w.webContents.audioMuted).to.be.false();
  914. });
  915. });
  916. describe('zoom api', () => {
  917. const hostZoomMap: Record<string, number> = {
  918. host1: 0.3,
  919. host2: 0.7,
  920. host3: 0.2
  921. };
  922. before(() => {
  923. const protocol = session.defaultSession.protocol;
  924. protocol.registerStringProtocol(standardScheme, (request, callback) => {
  925. const response = `<script>
  926. const {ipcRenderer} = require('electron')
  927. ipcRenderer.send('set-zoom', window.location.hostname)
  928. ipcRenderer.on(window.location.hostname + '-zoom-set', () => {
  929. ipcRenderer.send(window.location.hostname + '-zoom-level')
  930. })
  931. </script>`;
  932. callback({ data: response, mimeType: 'text/html' });
  933. });
  934. });
  935. after(() => {
  936. const protocol = session.defaultSession.protocol;
  937. protocol.unregisterProtocol(standardScheme);
  938. });
  939. afterEach(closeAllWindows);
  940. it('throws on an invalid zoomFactor', async () => {
  941. const w = new BrowserWindow({ show: false });
  942. await w.loadURL('about:blank');
  943. expect(() => {
  944. w.webContents.setZoomFactor(0.0);
  945. }).to.throw(/'zoomFactor' must be a double greater than 0.0/);
  946. expect(() => {
  947. w.webContents.setZoomFactor(-2.0);
  948. }).to.throw(/'zoomFactor' must be a double greater than 0.0/);
  949. });
  950. it('can set the correct zoom level (functions)', async () => {
  951. const w = new BrowserWindow({ show: false });
  952. try {
  953. await w.loadURL('about:blank');
  954. const zoomLevel = w.webContents.getZoomLevel();
  955. expect(zoomLevel).to.eql(0.0);
  956. w.webContents.setZoomLevel(0.5);
  957. const newZoomLevel = w.webContents.getZoomLevel();
  958. expect(newZoomLevel).to.eql(0.5);
  959. } finally {
  960. w.webContents.setZoomLevel(0);
  961. }
  962. });
  963. it('can set the correct zoom level (properties)', async () => {
  964. const w = new BrowserWindow({ show: false });
  965. try {
  966. await w.loadURL('about:blank');
  967. const zoomLevel = w.webContents.zoomLevel;
  968. expect(zoomLevel).to.eql(0.0);
  969. w.webContents.zoomLevel = 0.5;
  970. const newZoomLevel = w.webContents.zoomLevel;
  971. expect(newZoomLevel).to.eql(0.5);
  972. } finally {
  973. w.webContents.zoomLevel = 0;
  974. }
  975. });
  976. it('can set the correct zoom factor (functions)', async () => {
  977. const w = new BrowserWindow({ show: false });
  978. try {
  979. await w.loadURL('about:blank');
  980. const zoomFactor = w.webContents.getZoomFactor();
  981. expect(zoomFactor).to.eql(1.0);
  982. w.webContents.setZoomFactor(0.5);
  983. const newZoomFactor = w.webContents.getZoomFactor();
  984. expect(newZoomFactor).to.eql(0.5);
  985. } finally {
  986. w.webContents.setZoomFactor(1.0);
  987. }
  988. });
  989. it('can set the correct zoom factor (properties)', async () => {
  990. const w = new BrowserWindow({ show: false });
  991. try {
  992. await w.loadURL('about:blank');
  993. const zoomFactor = w.webContents.zoomFactor;
  994. expect(zoomFactor).to.eql(1.0);
  995. w.webContents.zoomFactor = 0.5;
  996. const newZoomFactor = w.webContents.zoomFactor;
  997. expect(newZoomFactor).to.eql(0.5);
  998. } finally {
  999. w.webContents.zoomFactor = 1.0;
  1000. }
  1001. });
  1002. it('can persist zoom level across navigation', (done) => {
  1003. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1004. let finalNavigation = false;
  1005. ipcMain.on('set-zoom', (e, host) => {
  1006. const zoomLevel = hostZoomMap[host];
  1007. if (!finalNavigation) w.webContents.zoomLevel = zoomLevel;
  1008. e.sender.send(`${host}-zoom-set`);
  1009. });
  1010. ipcMain.on('host1-zoom-level', (e) => {
  1011. try {
  1012. const zoomLevel = e.sender.getZoomLevel();
  1013. const expectedZoomLevel = hostZoomMap.host1;
  1014. expect(zoomLevel).to.equal(expectedZoomLevel);
  1015. if (finalNavigation) {
  1016. done();
  1017. } else {
  1018. w.loadURL(`${standardScheme}://host2`);
  1019. }
  1020. } catch (e) {
  1021. done(e);
  1022. }
  1023. });
  1024. ipcMain.once('host2-zoom-level', (e) => {
  1025. try {
  1026. const zoomLevel = e.sender.getZoomLevel();
  1027. const expectedZoomLevel = hostZoomMap.host2;
  1028. expect(zoomLevel).to.equal(expectedZoomLevel);
  1029. finalNavigation = true;
  1030. w.webContents.goBack();
  1031. } catch (e) {
  1032. done(e);
  1033. }
  1034. });
  1035. w.loadURL(`${standardScheme}://host1`);
  1036. });
  1037. it('can propagate zoom level across same session', async () => {
  1038. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  1039. const w2 = new BrowserWindow({ show: false });
  1040. defer(() => {
  1041. w2.setClosable(true);
  1042. w2.close();
  1043. });
  1044. await w.loadURL(`${standardScheme}://host3`);
  1045. w.webContents.zoomLevel = hostZoomMap.host3;
  1046. await w2.loadURL(`${standardScheme}://host3`);
  1047. const zoomLevel1 = w.webContents.zoomLevel;
  1048. expect(zoomLevel1).to.equal(hostZoomMap.host3);
  1049. const zoomLevel2 = w2.webContents.zoomLevel;
  1050. expect(zoomLevel1).to.equal(zoomLevel2);
  1051. });
  1052. it('cannot propagate zoom level across different session', async () => {
  1053. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  1054. const w2 = new BrowserWindow({
  1055. show: false,
  1056. webPreferences: {
  1057. partition: 'temp'
  1058. }
  1059. });
  1060. const protocol = w2.webContents.session.protocol;
  1061. protocol.registerStringProtocol(standardScheme, (request, callback) => {
  1062. callback('hello');
  1063. });
  1064. defer(() => {
  1065. w2.setClosable(true);
  1066. w2.close();
  1067. protocol.unregisterProtocol(standardScheme);
  1068. });
  1069. await w.loadURL(`${standardScheme}://host3`);
  1070. w.webContents.zoomLevel = hostZoomMap.host3;
  1071. await w2.loadURL(`${standardScheme}://host3`);
  1072. const zoomLevel1 = w.webContents.zoomLevel;
  1073. expect(zoomLevel1).to.equal(hostZoomMap.host3);
  1074. const zoomLevel2 = w2.webContents.zoomLevel;
  1075. expect(zoomLevel2).to.equal(0);
  1076. expect(zoomLevel1).to.not.equal(zoomLevel2);
  1077. });
  1078. it('can persist when it contains iframe', (done) => {
  1079. const w = new BrowserWindow({ show: false });
  1080. const server = http.createServer((req, res) => {
  1081. setTimeout(200).then(() => {
  1082. res.end();
  1083. });
  1084. });
  1085. listen(server).then(({ url }) => {
  1086. const content = `<iframe src=${url}></iframe>`;
  1087. w.webContents.on('did-frame-finish-load', (e, isMainFrame) => {
  1088. if (!isMainFrame) {
  1089. try {
  1090. const zoomLevel = w.webContents.zoomLevel;
  1091. expect(zoomLevel).to.equal(2.0);
  1092. w.webContents.zoomLevel = 0;
  1093. done();
  1094. } catch (e) {
  1095. done(e);
  1096. } finally {
  1097. server.close();
  1098. }
  1099. }
  1100. });
  1101. w.webContents.on('dom-ready', () => {
  1102. w.webContents.zoomLevel = 2.0;
  1103. });
  1104. w.loadURL(`data:text/html,${content}`);
  1105. });
  1106. });
  1107. it('cannot propagate when used with webframe', async () => {
  1108. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1109. const w2 = new BrowserWindow({ show: false });
  1110. const temporaryZoomSet = once(ipcMain, 'temporary-zoom-set');
  1111. w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html'));
  1112. await temporaryZoomSet;
  1113. const finalZoomLevel = w.webContents.getZoomLevel();
  1114. await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html'));
  1115. const zoomLevel1 = w.webContents.zoomLevel;
  1116. const zoomLevel2 = w2.webContents.zoomLevel;
  1117. w2.setClosable(true);
  1118. w2.close();
  1119. expect(zoomLevel1).to.equal(finalZoomLevel);
  1120. expect(zoomLevel2).to.equal(0);
  1121. expect(zoomLevel1).to.not.equal(zoomLevel2);
  1122. });
  1123. describe('with unique domains', () => {
  1124. let server: http.Server;
  1125. let serverUrl: string;
  1126. let crossSiteUrl: string;
  1127. before(async () => {
  1128. server = http.createServer((req, res) => {
  1129. setTimeout().then(() => res.end('hey'));
  1130. });
  1131. serverUrl = (await listen(server)).url;
  1132. crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
  1133. });
  1134. after(() => {
  1135. server.close();
  1136. });
  1137. it('cannot persist zoom level after navigation with webFrame', async () => {
  1138. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1139. const source = `
  1140. const {ipcRenderer, webFrame} = require('electron')
  1141. webFrame.setZoomLevel(0.6)
  1142. ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel())
  1143. `;
  1144. const zoomLevelPromise = once(ipcMain, 'zoom-level-set');
  1145. await w.loadURL(serverUrl);
  1146. await w.webContents.executeJavaScript(source);
  1147. let [, zoomLevel] = await zoomLevelPromise;
  1148. expect(zoomLevel).to.equal(0.6);
  1149. const loadPromise = once(w.webContents, 'did-finish-load');
  1150. await w.loadURL(crossSiteUrl);
  1151. await loadPromise;
  1152. zoomLevel = w.webContents.zoomLevel;
  1153. expect(zoomLevel).to.equal(0);
  1154. });
  1155. });
  1156. });
  1157. describe('webrtc ip policy api', () => {
  1158. afterEach(closeAllWindows);
  1159. it('can set and get webrtc ip policies', () => {
  1160. const w = new BrowserWindow({ show: false });
  1161. const policies = [
  1162. 'default',
  1163. 'default_public_interface_only',
  1164. 'default_public_and_private_interfaces',
  1165. 'disable_non_proxied_udp'
  1166. ] as const;
  1167. for (const policy of policies) {
  1168. w.webContents.setWebRTCIPHandlingPolicy(policy);
  1169. expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy);
  1170. }
  1171. });
  1172. });
  1173. describe('webrtc udp port range policy api', () => {
  1174. let w: BrowserWindow;
  1175. beforeEach(() => {
  1176. w = new BrowserWindow({ show: false });
  1177. });
  1178. afterEach(closeAllWindows);
  1179. it('check default webrtc udp port range is { min: 0, max: 0 }', () => {
  1180. const settings = w.webContents.getWebRTCUDPPortRange();
  1181. expect(settings).to.deep.equal({ min: 0, max: 0 });
  1182. });
  1183. it('can set and get webrtc udp port range policy with correct arguments', () => {
  1184. w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 });
  1185. const settings = w.webContents.getWebRTCUDPPortRange();
  1186. expect(settings).to.deep.equal({ min: 1, max: 65535 });
  1187. });
  1188. it('can not set webrtc udp port range policy with invalid arguments', () => {
  1189. expect(() => {
  1190. w.webContents.setWebRTCUDPPortRange({ min: 0, max: 65535 });
  1191. }).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]");
  1192. expect(() => {
  1193. w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65536 });
  1194. }).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]");
  1195. expect(() => {
  1196. w.webContents.setWebRTCUDPPortRange({ min: 60000, max: 56789 });
  1197. }).to.throw("'max' must be greater than or equal to 'min'");
  1198. });
  1199. it('can reset webrtc udp port range policy to default with { min: 0, max: 0 }', () => {
  1200. w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 });
  1201. const settings = w.webContents.getWebRTCUDPPortRange();
  1202. expect(settings).to.deep.equal({ min: 1, max: 65535 });
  1203. w.webContents.setWebRTCUDPPortRange({ min: 0, max: 0 });
  1204. const defaultSetting = w.webContents.getWebRTCUDPPortRange();
  1205. expect(defaultSetting).to.deep.equal({ min: 0, max: 0 });
  1206. });
  1207. });
  1208. describe('opener api', () => {
  1209. afterEach(closeAllWindows);
  1210. it('can get opener with window.open()', async () => {
  1211. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1212. await w.loadURL('about:blank');
  1213. const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
  1214. w.webContents.executeJavaScript('window.open("about:blank")', true);
  1215. const [childWindow] = await childPromise;
  1216. expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
  1217. });
  1218. it('has no opener when using "noopener"', async () => {
  1219. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1220. await w.loadURL('about:blank');
  1221. const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
  1222. w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true);
  1223. const [childWindow] = await childPromise;
  1224. expect(childWindow.webContents.opener).to.be.null();
  1225. });
  1226. it('can get opener with a[target=_blank][rel=opener]', async () => {
  1227. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1228. await w.loadURL('about:blank');
  1229. const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
  1230. w.webContents.executeJavaScript(`(function() {
  1231. const a = document.createElement('a');
  1232. a.target = '_blank';
  1233. a.rel = 'opener';
  1234. a.href = 'about:blank';
  1235. a.click();
  1236. }())`, true);
  1237. const [childWindow] = await childPromise;
  1238. expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
  1239. });
  1240. it('has no opener with a[target=_blank][rel=noopener]', async () => {
  1241. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1242. await w.loadURL('about:blank');
  1243. const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
  1244. w.webContents.executeJavaScript(`(function() {
  1245. const a = document.createElement('a');
  1246. a.target = '_blank';
  1247. a.rel = 'noopener';
  1248. a.href = 'about:blank';
  1249. a.click();
  1250. }())`, true);
  1251. const [childWindow] = await childPromise;
  1252. expect(childWindow.webContents.opener).to.be.null();
  1253. });
  1254. });
  1255. describe('render view deleted events', () => {
  1256. let server: http.Server;
  1257. let serverUrl: string;
  1258. let crossSiteUrl: string;
  1259. before(async () => {
  1260. server = http.createServer((req, res) => {
  1261. const respond = () => {
  1262. if (req.url === '/redirect-cross-site') {
  1263. res.setHeader('Location', `${crossSiteUrl}/redirected`);
  1264. res.statusCode = 302;
  1265. res.end();
  1266. } else if (req.url === '/redirected') {
  1267. res.end('<html><script>window.localStorage</script></html>');
  1268. } else if (req.url === '/first-window-open') {
  1269. res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`);
  1270. } else if (req.url === '/second-window-open') {
  1271. res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>');
  1272. } else {
  1273. res.end();
  1274. }
  1275. };
  1276. setTimeout().then(respond);
  1277. });
  1278. serverUrl = (await listen(server)).url;
  1279. crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
  1280. });
  1281. after(() => {
  1282. server.close();
  1283. });
  1284. afterEach(closeAllWindows);
  1285. it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
  1286. const w = new BrowserWindow({ show: false });
  1287. let currentRenderViewDeletedEmitted = false;
  1288. const renderViewDeletedHandler = () => {
  1289. currentRenderViewDeletedEmitted = true;
  1290. };
  1291. w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
  1292. w.webContents.on('did-finish-load', () => {
  1293. w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
  1294. w.close();
  1295. });
  1296. const destroyed = once(w.webContents, 'destroyed');
  1297. w.loadURL(`${serverUrl}/redirect-cross-site`);
  1298. await destroyed;
  1299. expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted');
  1300. });
  1301. it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
  1302. const parentWindow = new BrowserWindow({ show: false });
  1303. let currentRenderViewDeletedEmitted = false;
  1304. let childWindow: BrowserWindow | null = null;
  1305. const destroyed = once(parentWindow.webContents, 'destroyed');
  1306. const renderViewDeletedHandler = () => {
  1307. currentRenderViewDeletedEmitted = true;
  1308. };
  1309. const childWindowCreated = new Promise<void>((resolve) => {
  1310. app.once('browser-window-created', (event, window) => {
  1311. childWindow = window;
  1312. window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
  1313. resolve();
  1314. });
  1315. });
  1316. parentWindow.loadURL(`${serverUrl}/first-window-open`);
  1317. await childWindowCreated;
  1318. childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
  1319. parentWindow.close();
  1320. await destroyed;
  1321. expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed');
  1322. });
  1323. it('emits current-render-view-deleted if the current RVHs are deleted', async () => {
  1324. const w = new BrowserWindow({ show: false });
  1325. let currentRenderViewDeletedEmitted = false;
  1326. w.webContents.on('current-render-view-deleted' as any, () => {
  1327. currentRenderViewDeletedEmitted = true;
  1328. });
  1329. w.webContents.on('did-finish-load', () => {
  1330. w.close();
  1331. });
  1332. const destroyed = once(w.webContents, 'destroyed');
  1333. w.loadURL(`${serverUrl}/redirect-cross-site`);
  1334. await destroyed;
  1335. expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted');
  1336. });
  1337. it('emits render-view-deleted if any RVHs are deleted', async () => {
  1338. const w = new BrowserWindow({ show: false });
  1339. let rvhDeletedCount = 0;
  1340. w.webContents.on('render-view-deleted' as any, () => {
  1341. rvhDeletedCount++;
  1342. });
  1343. w.webContents.on('did-finish-load', () => {
  1344. w.close();
  1345. });
  1346. const destroyed = once(w.webContents, 'destroyed');
  1347. w.loadURL(`${serverUrl}/redirect-cross-site`);
  1348. await destroyed;
  1349. const expectedRenderViewDeletedEventCount = 1;
  1350. expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times');
  1351. });
  1352. });
  1353. describe('setIgnoreMenuShortcuts(ignore)', () => {
  1354. afterEach(closeAllWindows);
  1355. it('does not throw', () => {
  1356. const w = new BrowserWindow({ show: false });
  1357. expect(() => {
  1358. w.webContents.setIgnoreMenuShortcuts(true);
  1359. w.webContents.setIgnoreMenuShortcuts(false);
  1360. }).to.not.throw();
  1361. });
  1362. });
  1363. const crashPrefs = [
  1364. {
  1365. nodeIntegration: true
  1366. },
  1367. {
  1368. sandbox: true
  1369. }
  1370. ];
  1371. const nicePrefs = (o: any) => {
  1372. let s = '';
  1373. for (const key of Object.keys(o)) {
  1374. s += `${key}=${o[key]}, `;
  1375. }
  1376. return `(${s.slice(0, s.length - 2)})`;
  1377. };
  1378. for (const prefs of crashPrefs) {
  1379. describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => {
  1380. let w: BrowserWindow;
  1381. beforeEach(async () => {
  1382. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  1383. await w.loadURL('about:blank');
  1384. });
  1385. afterEach(closeAllWindows);
  1386. it('isCrashed() is false by default', () => {
  1387. expect(w.webContents.isCrashed()).to.equal(false);
  1388. });
  1389. it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => {
  1390. expect(w.webContents.isCrashed()).to.equal(false);
  1391. const crashEvent = once(w.webContents, 'render-process-gone') as Promise<[any, Electron.RenderProcessGoneDetails]>;
  1392. w.webContents.forcefullyCrashRenderer();
  1393. const [, details] = await crashEvent;
  1394. expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed');
  1395. expect(w.webContents.isCrashed()).to.equal(true);
  1396. });
  1397. it('a crashed process is recoverable with reload()', async () => {
  1398. expect(w.webContents.isCrashed()).to.equal(false);
  1399. w.webContents.forcefullyCrashRenderer();
  1400. w.webContents.reload();
  1401. expect(w.webContents.isCrashed()).to.equal(false);
  1402. });
  1403. });
  1404. }
  1405. // Destroying webContents in its event listener is going to crash when
  1406. // Electron is built in Debug mode.
  1407. describe('destroy()', () => {
  1408. let server: http.Server;
  1409. let serverUrl: string;
  1410. before((done) => {
  1411. server = http.createServer((request, response) => {
  1412. switch (request.url) {
  1413. case '/net-error':
  1414. response.destroy();
  1415. break;
  1416. case '/200':
  1417. response.end();
  1418. break;
  1419. default:
  1420. done('unsupported endpoint');
  1421. }
  1422. });
  1423. listen(server).then(({ url }) => {
  1424. serverUrl = url;
  1425. done();
  1426. });
  1427. });
  1428. after(() => {
  1429. server.close();
  1430. });
  1431. const events = [
  1432. { name: 'did-start-loading', url: '/200' },
  1433. { name: 'dom-ready', url: '/200' },
  1434. { name: 'did-stop-loading', url: '/200' },
  1435. { name: 'did-finish-load', url: '/200' },
  1436. // FIXME: Multiple Emit calls inside an observer assume that object
  1437. // will be alive till end of the observer. Synchronous `destroy` api
  1438. // violates this contract and crashes.
  1439. { name: 'did-frame-finish-load', url: '/200' },
  1440. { name: 'did-fail-load', url: '/net-error' }
  1441. ];
  1442. for (const e of events) {
  1443. it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () {
  1444. // This test is flaky on Windows CI and we don't know why, but the
  1445. // purpose of this test is to make sure Electron does not crash so it
  1446. // is fine to retry this test for a few times.
  1447. this.retries(3);
  1448. const contents = (webContents as typeof ElectronInternal.WebContents).create();
  1449. const originalEmit = contents.emit.bind(contents);
  1450. contents.emit = (...args) => { return originalEmit(...args); };
  1451. contents.once(e.name as any, () => contents.destroy());
  1452. const destroyed = once(contents, 'destroyed');
  1453. contents.loadURL(serverUrl + e.url);
  1454. await destroyed;
  1455. });
  1456. }
  1457. });
  1458. describe('did-change-theme-color event', () => {
  1459. afterEach(closeAllWindows);
  1460. it('is triggered with correct theme color', (done) => {
  1461. const w = new BrowserWindow({ show: true });
  1462. let count = 0;
  1463. w.webContents.on('did-change-theme-color', (e, color) => {
  1464. try {
  1465. if (count === 0) {
  1466. count += 1;
  1467. expect(color).to.equal('#FFEEDD');
  1468. w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  1469. } else if (count === 1) {
  1470. expect(color).to.be.null();
  1471. done();
  1472. }
  1473. } catch (e) {
  1474. done(e);
  1475. }
  1476. });
  1477. w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html'));
  1478. });
  1479. });
  1480. describe('console-message event', () => {
  1481. afterEach(closeAllWindows);
  1482. it('is triggered with correct log message', (done) => {
  1483. const w = new BrowserWindow({ show: true });
  1484. w.webContents.on('console-message', (e, level, message) => {
  1485. // Don't just assert as Chromium might emit other logs that we should ignore.
  1486. if (message === 'a') {
  1487. done();
  1488. }
  1489. });
  1490. w.loadFile(path.join(fixturesPath, 'pages', 'a.html'));
  1491. });
  1492. });
  1493. describe('ipc-message event', () => {
  1494. afterEach(closeAllWindows);
  1495. it('emits when the renderer process sends an asynchronous message', async () => {
  1496. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1497. await w.webContents.loadURL('about:blank');
  1498. w.webContents.executeJavaScript(`
  1499. require('electron').ipcRenderer.send('message', 'Hello World!')
  1500. `);
  1501. const [, channel, message] = await once(w.webContents, 'ipc-message');
  1502. expect(channel).to.equal('message');
  1503. expect(message).to.equal('Hello World!');
  1504. });
  1505. });
  1506. describe('ipc-message-sync event', () => {
  1507. afterEach(closeAllWindows);
  1508. it('emits when the renderer process sends a synchronous message', async () => {
  1509. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1510. await w.webContents.loadURL('about:blank');
  1511. const promise: Promise<[string, string]> = new Promise(resolve => {
  1512. w.webContents.once('ipc-message-sync', (event, channel, arg) => {
  1513. event.returnValue = 'foobar';
  1514. resolve([channel, arg]);
  1515. });
  1516. });
  1517. const result = await w.webContents.executeJavaScript(`
  1518. require('electron').ipcRenderer.sendSync('message', 'Hello World!')
  1519. `);
  1520. const [channel, message] = await promise;
  1521. expect(channel).to.equal('message');
  1522. expect(message).to.equal('Hello World!');
  1523. expect(result).to.equal('foobar');
  1524. });
  1525. });
  1526. describe('referrer', () => {
  1527. afterEach(closeAllWindows);
  1528. it('propagates referrer information to new target=_blank windows', (done) => {
  1529. const w = new BrowserWindow({ show: false });
  1530. const server = http.createServer((req, res) => {
  1531. if (req.url === '/should_have_referrer') {
  1532. try {
  1533. expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
  1534. return done();
  1535. } catch (e) {
  1536. return done(e);
  1537. } finally {
  1538. server.close();
  1539. }
  1540. }
  1541. res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>');
  1542. });
  1543. listen(server).then(({ url }) => {
  1544. w.webContents.once('did-finish-load', () => {
  1545. w.webContents.setWindowOpenHandler(details => {
  1546. expect(details.referrer.url).to.equal(url + '/');
  1547. expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
  1548. return { action: 'allow' };
  1549. });
  1550. w.webContents.executeJavaScript('a.click()');
  1551. });
  1552. w.loadURL(url);
  1553. });
  1554. });
  1555. it('propagates referrer information to windows opened with window.open', (done) => {
  1556. const w = new BrowserWindow({ show: false });
  1557. const server = http.createServer((req, res) => {
  1558. if (req.url === '/should_have_referrer') {
  1559. try {
  1560. expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
  1561. return done();
  1562. } catch (e) {
  1563. return done(e);
  1564. }
  1565. }
  1566. res.end('');
  1567. });
  1568. listen(server).then(({ url }) => {
  1569. w.webContents.once('did-finish-load', () => {
  1570. w.webContents.setWindowOpenHandler(details => {
  1571. expect(details.referrer.url).to.equal(url + '/');
  1572. expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
  1573. return { action: 'allow' };
  1574. });
  1575. w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")');
  1576. });
  1577. w.loadURL(url);
  1578. });
  1579. });
  1580. });
  1581. describe('webframe messages in sandboxed contents', () => {
  1582. afterEach(closeAllWindows);
  1583. it('responds to executeJavaScript', async () => {
  1584. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1585. await w.loadURL('about:blank');
  1586. const result = await w.webContents.executeJavaScript('37 + 5');
  1587. expect(result).to.equal(42);
  1588. });
  1589. });
  1590. describe('preload-error event', () => {
  1591. afterEach(closeAllWindows);
  1592. const generateSpecs = (description: string, sandbox: boolean) => {
  1593. describe(description, () => {
  1594. it('is triggered when unhandled exception is thrown', async () => {
  1595. const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js');
  1596. const w = new BrowserWindow({
  1597. show: false,
  1598. webPreferences: {
  1599. sandbox,
  1600. preload
  1601. }
  1602. });
  1603. const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
  1604. w.loadURL('about:blank');
  1605. const [, preloadPath, error] = await promise;
  1606. expect(preloadPath).to.equal(preload);
  1607. expect(error.message).to.equal('Hello World!');
  1608. });
  1609. it('is triggered on syntax errors', async () => {
  1610. const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js');
  1611. const w = new BrowserWindow({
  1612. show: false,
  1613. webPreferences: {
  1614. sandbox,
  1615. preload
  1616. }
  1617. });
  1618. const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
  1619. w.loadURL('about:blank');
  1620. const [, preloadPath, error] = await promise;
  1621. expect(preloadPath).to.equal(preload);
  1622. expect(error.message).to.equal('foobar is not defined');
  1623. });
  1624. it('is triggered when preload script loading fails', async () => {
  1625. const preload = path.join(fixturesPath, 'module', 'preload-invalid.js');
  1626. const w = new BrowserWindow({
  1627. show: false,
  1628. webPreferences: {
  1629. sandbox,
  1630. preload
  1631. }
  1632. });
  1633. const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
  1634. w.loadURL('about:blank');
  1635. const [, preloadPath, error] = await promise;
  1636. expect(preloadPath).to.equal(preload);
  1637. expect(error.message).to.contain('preload-invalid.js');
  1638. });
  1639. });
  1640. };
  1641. generateSpecs('without sandbox', false);
  1642. generateSpecs('with sandbox', true);
  1643. });
  1644. describe('takeHeapSnapshot()', () => {
  1645. afterEach(closeAllWindows);
  1646. it('works with sandboxed renderers', async () => {
  1647. const w = new BrowserWindow({
  1648. show: false,
  1649. webPreferences: {
  1650. sandbox: true
  1651. }
  1652. });
  1653. await w.loadURL('about:blank');
  1654. const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
  1655. const cleanup = () => {
  1656. try {
  1657. fs.unlinkSync(filePath);
  1658. } catch {
  1659. // ignore error
  1660. }
  1661. };
  1662. try {
  1663. await w.webContents.takeHeapSnapshot(filePath);
  1664. const stats = fs.statSync(filePath);
  1665. expect(stats.size).not.to.be.equal(0);
  1666. } finally {
  1667. cleanup();
  1668. }
  1669. });
  1670. it('fails with invalid file path', async () => {
  1671. const w = new BrowserWindow({
  1672. show: false,
  1673. webPreferences: {
  1674. sandbox: true
  1675. }
  1676. });
  1677. await w.loadURL('about:blank');
  1678. const badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path');
  1679. const promise = w.webContents.takeHeapSnapshot(badPath);
  1680. return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`);
  1681. });
  1682. it('fails with invalid render process', async () => {
  1683. const w = new BrowserWindow({
  1684. show: false,
  1685. webPreferences: {
  1686. sandbox: true
  1687. }
  1688. });
  1689. const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
  1690. w.webContents.destroy();
  1691. const promise = w.webContents.takeHeapSnapshot(filePath);
  1692. return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame');
  1693. });
  1694. });
  1695. describe('setBackgroundThrottling()', () => {
  1696. afterEach(closeAllWindows);
  1697. it('does not crash when allowing', () => {
  1698. const w = new BrowserWindow({ show: false });
  1699. w.webContents.setBackgroundThrottling(true);
  1700. });
  1701. it('does not crash when called via BrowserWindow', () => {
  1702. const w = new BrowserWindow({ show: false });
  1703. w.setBackgroundThrottling(true);
  1704. });
  1705. it('does not crash when disallowing', () => {
  1706. const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } });
  1707. w.webContents.setBackgroundThrottling(false);
  1708. });
  1709. });
  1710. describe('getBackgroundThrottling()', () => {
  1711. afterEach(closeAllWindows);
  1712. it('works via getter', () => {
  1713. const w = new BrowserWindow({ show: false });
  1714. w.webContents.setBackgroundThrottling(false);
  1715. expect(w.webContents.getBackgroundThrottling()).to.equal(false);
  1716. w.webContents.setBackgroundThrottling(true);
  1717. expect(w.webContents.getBackgroundThrottling()).to.equal(true);
  1718. });
  1719. it('works via property', () => {
  1720. const w = new BrowserWindow({ show: false });
  1721. w.webContents.backgroundThrottling = false;
  1722. expect(w.webContents.backgroundThrottling).to.equal(false);
  1723. w.webContents.backgroundThrottling = true;
  1724. expect(w.webContents.backgroundThrottling).to.equal(true);
  1725. });
  1726. it('works via BrowserWindow', () => {
  1727. const w = new BrowserWindow({ show: false });
  1728. w.setBackgroundThrottling(false);
  1729. expect(w.getBackgroundThrottling()).to.equal(false);
  1730. w.setBackgroundThrottling(true);
  1731. expect(w.getBackgroundThrottling()).to.equal(true);
  1732. });
  1733. });
  1734. ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => {
  1735. afterEach(closeAllWindows);
  1736. it('can get printer list', async () => {
  1737. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1738. await w.loadURL('about:blank');
  1739. const printers = await w.webContents.getPrintersAsync();
  1740. expect(printers).to.be.an('array');
  1741. });
  1742. });
  1743. ifdescribe(features.isPrintingEnabled())('printToPDF()', () => {
  1744. let w: BrowserWindow;
  1745. beforeEach(() => {
  1746. w = new BrowserWindow({
  1747. show: false,
  1748. webPreferences: {
  1749. sandbox: true
  1750. }
  1751. });
  1752. });
  1753. afterEach(closeAllWindows);
  1754. it('rejects on incorrectly typed parameters', async () => {
  1755. const badTypes = {
  1756. landscape: [],
  1757. displayHeaderFooter: '123',
  1758. printBackground: 2,
  1759. scale: 'not-a-number',
  1760. pageSize: 'IAmAPageSize',
  1761. margins: 'terrible',
  1762. pageRanges: { oops: 'im-not-the-right-key' },
  1763. headerTemplate: [1, 2, 3],
  1764. footerTemplate: [4, 5, 6],
  1765. preferCSSPageSize: 'no'
  1766. };
  1767. await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
  1768. // These will hard crash in Chromium unless we type-check
  1769. for (const [key, value] of Object.entries(badTypes)) {
  1770. const param = { [key]: value };
  1771. await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected();
  1772. }
  1773. });
  1774. it('does not crash when called multiple times in parallel', async () => {
  1775. await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
  1776. const promises = [];
  1777. for (let i = 0; i < 3; i++) {
  1778. promises.push(w.webContents.printToPDF({}));
  1779. }
  1780. const results = await Promise.all(promises);
  1781. for (const data of results) {
  1782. expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
  1783. }
  1784. });
  1785. it('does not crash when called multiple times in sequence', async () => {
  1786. await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
  1787. const results = [];
  1788. for (let i = 0; i < 3; i++) {
  1789. const result = await w.webContents.printToPDF({});
  1790. results.push(result);
  1791. }
  1792. for (const data of results) {
  1793. expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
  1794. }
  1795. });
  1796. it('can print a PDF with default settings', async () => {
  1797. await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
  1798. const data = await w.webContents.printToPDF({});
  1799. expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
  1800. });
  1801. type PageSizeString = Exclude<Required<Electron.PrintToPDFOptions>['pageSize'], Electron.Size>;
  1802. it('with custom page sizes', async () => {
  1803. const paperFormats: Record<PageSizeString, ElectronInternal.PageSize> = {
  1804. Letter: { width: 8.5, height: 11 },
  1805. Legal: { width: 8.5, height: 14 },
  1806. Tabloid: { width: 11, height: 17 },
  1807. Ledger: { width: 17, height: 11 },
  1808. A0: { width: 33.1, height: 46.8 },
  1809. A1: { width: 23.4, height: 33.1 },
  1810. A2: { width: 16.54, height: 23.4 },
  1811. A3: { width: 11.7, height: 16.54 },
  1812. A4: { width: 8.27, height: 11.7 },
  1813. A5: { width: 5.83, height: 8.27 },
  1814. A6: { width: 4.13, height: 5.83 }
  1815. };
  1816. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
  1817. for (const format of Object.keys(paperFormats) as PageSizeString[]) {
  1818. const data = await w.webContents.printToPDF({ pageSize: format });
  1819. const doc = await pdfjs.getDocument(data).promise;
  1820. const page = await doc.getPage(1);
  1821. // page.view is [top, left, width, height].
  1822. const width = page.view[2] / 72;
  1823. const height = page.view[3] / 72;
  1824. const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon;
  1825. expect(approxEq(width, paperFormats[format].width)).to.be.true();
  1826. expect(approxEq(height, paperFormats[format].height)).to.be.true();
  1827. }
  1828. });
  1829. it('with custom header and footer', async () => {
  1830. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
  1831. const data = await w.webContents.printToPDF({
  1832. displayHeaderFooter: true,
  1833. headerTemplate: '<div>I\'m a PDF header</div>',
  1834. footerTemplate: '<div>I\'m a PDF footer</div>'
  1835. });
  1836. const doc = await pdfjs.getDocument(data).promise;
  1837. const page = await doc.getPage(1);
  1838. const { items } = await page.getTextContent();
  1839. // Check that generated PDF contains a header.
  1840. const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text));
  1841. expect(containsText(/I'm a PDF header/)).to.be.true();
  1842. expect(containsText(/I'm a PDF footer/)).to.be.true();
  1843. });
  1844. it('in landscape mode', async () => {
  1845. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
  1846. const data = await w.webContents.printToPDF({ landscape: true });
  1847. const doc = await pdfjs.getDocument(data).promise;
  1848. const page = await doc.getPage(1);
  1849. // page.view is [top, left, width, height].
  1850. const width = page.view[2];
  1851. const height = page.view[3];
  1852. expect(width).to.be.greaterThan(height);
  1853. });
  1854. it('with custom page ranges', async () => {
  1855. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html'));
  1856. const data = await w.webContents.printToPDF({
  1857. pageRanges: '1-3',
  1858. landscape: true
  1859. });
  1860. const doc = await pdfjs.getDocument(data).promise;
  1861. // Check that correct # of pages are rendered.
  1862. expect(doc.numPages).to.equal(3);
  1863. });
  1864. it('does not tag PDFs by default', async () => {
  1865. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
  1866. const data = await w.webContents.printToPDF({});
  1867. const doc = await pdfjs.getDocument(data).promise;
  1868. const markInfo = await doc.getMarkInfo();
  1869. expect(markInfo).to.be.null();
  1870. });
  1871. it('can generate tag data for PDFs', async () => {
  1872. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
  1873. const data = await w.webContents.printToPDF({ generateTaggedPDF: true });
  1874. const doc = await pdfjs.getDocument(data).promise;
  1875. const markInfo = await doc.getMarkInfo();
  1876. expect(markInfo).to.deep.equal({
  1877. Marked: true,
  1878. UserProperties: false,
  1879. Suspects: false
  1880. });
  1881. });
  1882. });
  1883. describe('PictureInPicture video', () => {
  1884. afterEach(closeAllWindows);
  1885. it('works as expected', async function () {
  1886. const w = new BrowserWindow({ webPreferences: { sandbox: true } });
  1887. // TODO(codebytere): figure out why this workaround is needed and remove.
  1888. // It is not germane to the actual test.
  1889. await w.loadFile(path.join(fixturesPath, 'blank.html'));
  1890. await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html'));
  1891. await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true);
  1892. const result = await w.webContents.executeJavaScript('runTest(true)', true);
  1893. expect(result).to.be.true();
  1894. });
  1895. });
  1896. describe('Shared Workers', () => {
  1897. afterEach(closeAllWindows);
  1898. it('can get multiple shared workers', async () => {
  1899. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1900. const ready = once(ipcMain, 'ready');
  1901. w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
  1902. await ready;
  1903. const sharedWorkers = w.webContents.getAllSharedWorkers();
  1904. expect(sharedWorkers).to.have.lengthOf(2);
  1905. expect(sharedWorkers[0].url).to.contain('shared-worker');
  1906. expect(sharedWorkers[1].url).to.contain('shared-worker');
  1907. });
  1908. it('can inspect a specific shared worker', async () => {
  1909. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1910. const ready = once(ipcMain, 'ready');
  1911. w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
  1912. await ready;
  1913. const sharedWorkers = w.webContents.getAllSharedWorkers();
  1914. const devtoolsOpened = once(w.webContents, 'devtools-opened');
  1915. w.webContents.inspectSharedWorkerById(sharedWorkers[0].id);
  1916. await devtoolsOpened;
  1917. const devtoolsClosed = once(w.webContents, 'devtools-closed');
  1918. w.webContents.closeDevTools();
  1919. await devtoolsClosed;
  1920. });
  1921. });
  1922. describe('login event', () => {
  1923. afterEach(closeAllWindows);
  1924. let server: http.Server;
  1925. let serverUrl: string;
  1926. let serverPort: number;
  1927. let proxyServer: http.Server;
  1928. let proxyServerPort: number;
  1929. before(async () => {
  1930. server = http.createServer((request, response) => {
  1931. if (request.url === '/no-auth') {
  1932. return response.end('ok');
  1933. }
  1934. if (request.headers.authorization) {
  1935. response.writeHead(200, { 'Content-type': 'text/plain' });
  1936. return response.end(request.headers.authorization);
  1937. }
  1938. response
  1939. .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
  1940. .end('401');
  1941. });
  1942. ({ port: serverPort, url: serverUrl } = await listen(server));
  1943. });
  1944. before(async () => {
  1945. proxyServer = http.createServer((request, response) => {
  1946. if (request.headers['proxy-authorization']) {
  1947. response.writeHead(200, { 'Content-type': 'text/plain' });
  1948. return response.end(request.headers['proxy-authorization']);
  1949. }
  1950. response
  1951. .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' })
  1952. .end();
  1953. });
  1954. proxyServerPort = (await listen(proxyServer)).port;
  1955. });
  1956. afterEach(async () => {
  1957. await session.defaultSession.clearAuthCache();
  1958. });
  1959. after(() => {
  1960. server.close();
  1961. proxyServer.close();
  1962. });
  1963. it('is emitted when navigating', async () => {
  1964. const [user, pass] = ['user', 'pass'];
  1965. const w = new BrowserWindow({ show: false });
  1966. let eventRequest: any;
  1967. let eventAuthInfo: any;
  1968. w.webContents.on('login', (event, request, authInfo, cb) => {
  1969. eventRequest = request;
  1970. eventAuthInfo = authInfo;
  1971. event.preventDefault();
  1972. cb(user, pass);
  1973. });
  1974. await w.loadURL(serverUrl);
  1975. const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
  1976. expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
  1977. expect(eventRequest.url).to.equal(serverUrl + '/');
  1978. expect(eventAuthInfo.isProxy).to.be.false();
  1979. expect(eventAuthInfo.scheme).to.equal('basic');
  1980. expect(eventAuthInfo.host).to.equal('127.0.0.1');
  1981. expect(eventAuthInfo.port).to.equal(serverPort);
  1982. expect(eventAuthInfo.realm).to.equal('Foo');
  1983. });
  1984. it('is emitted when a proxy requests authorization', async () => {
  1985. const customSession = session.fromPartition(`${Math.random()}`);
  1986. await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' });
  1987. const [user, pass] = ['user', 'pass'];
  1988. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  1989. let eventRequest: any;
  1990. let eventAuthInfo: any;
  1991. w.webContents.on('login', (event, request, authInfo, cb) => {
  1992. eventRequest = request;
  1993. eventAuthInfo = authInfo;
  1994. event.preventDefault();
  1995. cb(user, pass);
  1996. });
  1997. await w.loadURL(`${serverUrl}/no-auth`);
  1998. const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
  1999. expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
  2000. expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`);
  2001. expect(eventAuthInfo.isProxy).to.be.true();
  2002. expect(eventAuthInfo.scheme).to.equal('basic');
  2003. expect(eventAuthInfo.host).to.equal('127.0.0.1');
  2004. expect(eventAuthInfo.port).to.equal(proxyServerPort);
  2005. expect(eventAuthInfo.realm).to.equal('Foo');
  2006. });
  2007. it('cancels authentication when callback is called with no arguments', async () => {
  2008. const w = new BrowserWindow({ show: false });
  2009. w.webContents.on('login', (event, request, authInfo, cb) => {
  2010. event.preventDefault();
  2011. cb();
  2012. });
  2013. await w.loadURL(serverUrl);
  2014. const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
  2015. expect(body).to.equal('401');
  2016. });
  2017. });
  2018. describe('page-title-updated event', () => {
  2019. afterEach(closeAllWindows);
  2020. it('is emitted with a full title for pages with no navigation', async () => {
  2021. const bw = new BrowserWindow({ show: false });
  2022. await bw.loadURL('about:blank');
  2023. bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null');
  2024. const [, child] = await once(app, 'web-contents-created') as [any, WebContents];
  2025. bw.webContents.executeJavaScript('child.document.title = "new title"');
  2026. const [, title] = await once(child, 'page-title-updated') as [any, string];
  2027. expect(title).to.equal('new title');
  2028. });
  2029. });
  2030. describe('crashed event', () => {
  2031. it('does not crash main process when destroying WebContents in it', async () => {
  2032. const contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true });
  2033. const crashEvent = once(contents, 'render-process-gone');
  2034. await contents.loadURL('about:blank');
  2035. contents.forcefullyCrashRenderer();
  2036. await crashEvent;
  2037. contents.destroy();
  2038. });
  2039. });
  2040. describe('context-menu event', () => {
  2041. afterEach(closeAllWindows);
  2042. it('emits when right-clicked in page', async () => {
  2043. const w = new BrowserWindow({ show: false });
  2044. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  2045. const promise = once(w.webContents, 'context-menu') as Promise<[any, Electron.ContextMenuParams]>;
  2046. // Simulate right-click to create context-menu event.
  2047. const opts = { x: 0, y: 0, button: 'right' as const };
  2048. w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' });
  2049. w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' });
  2050. const [, params] = await promise;
  2051. expect(params.pageURL).to.equal(w.webContents.getURL());
  2052. expect(params.frame).to.be.an('object');
  2053. expect(params.x).to.be.a('number');
  2054. expect(params.y).to.be.a('number');
  2055. });
  2056. });
  2057. describe('close() method', () => {
  2058. afterEach(closeAllWindows);
  2059. it('closes when close() is called', async () => {
  2060. const w = (webContents as typeof ElectronInternal.WebContents).create();
  2061. const destroyed = once(w, 'destroyed');
  2062. w.close();
  2063. await destroyed;
  2064. expect(w.isDestroyed()).to.be.true();
  2065. });
  2066. it('closes when close() is called after loading a page', async () => {
  2067. const w = (webContents as typeof ElectronInternal.WebContents).create();
  2068. await w.loadURL('about:blank');
  2069. const destroyed = once(w, 'destroyed');
  2070. w.close();
  2071. await destroyed;
  2072. expect(w.isDestroyed()).to.be.true();
  2073. });
  2074. it('can be GCed before loading a page', async () => {
  2075. const v8Util = process._linkedBinding('electron_common_v8_util');
  2076. let registry: FinalizationRegistry<unknown> | null = null;
  2077. const cleanedUp = new Promise<number>(resolve => {
  2078. registry = new FinalizationRegistry(resolve as any);
  2079. });
  2080. (() => {
  2081. const w = (webContents as typeof ElectronInternal.WebContents).create();
  2082. registry!.register(w, 42);
  2083. })();
  2084. const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100);
  2085. defer(() => clearInterval(i));
  2086. expect(await cleanedUp).to.equal(42);
  2087. });
  2088. it('causes its parent browserwindow to be closed', async () => {
  2089. const w = new BrowserWindow({ show: false });
  2090. await w.loadURL('about:blank');
  2091. const closed = once(w, 'closed');
  2092. w.webContents.close();
  2093. await closed;
  2094. expect(w.isDestroyed()).to.be.true();
  2095. });
  2096. it('ignores beforeunload if waitForBeforeUnload not specified', async () => {
  2097. const w = (webContents as typeof ElectronInternal.WebContents).create();
  2098. await w.loadURL('about:blank');
  2099. await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
  2100. w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); });
  2101. const destroyed = once(w, 'destroyed');
  2102. w.close();
  2103. await destroyed;
  2104. expect(w.isDestroyed()).to.be.true();
  2105. });
  2106. it('runs beforeunload if waitForBeforeUnload is specified', async () => {
  2107. const w = (webContents as typeof ElectronInternal.WebContents).create();
  2108. await w.loadURL('about:blank');
  2109. await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
  2110. const willPreventUnload = once(w, 'will-prevent-unload');
  2111. w.close({ waitForBeforeUnload: true });
  2112. await willPreventUnload;
  2113. expect(w.isDestroyed()).to.be.false();
  2114. });
  2115. it('overriding beforeunload prevention results in webcontents close', async () => {
  2116. const w = (webContents as typeof ElectronInternal.WebContents).create();
  2117. await w.loadURL('about:blank');
  2118. await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
  2119. w.once('will-prevent-unload', e => e.preventDefault());
  2120. const destroyed = once(w, 'destroyed');
  2121. w.close({ waitForBeforeUnload: true });
  2122. await destroyed;
  2123. expect(w.isDestroyed()).to.be.true();
  2124. });
  2125. });
  2126. describe('content-bounds-updated event', () => {
  2127. afterEach(closeAllWindows);
  2128. it('emits when moveTo is called', async () => {
  2129. const w = new BrowserWindow({ show: false });
  2130. w.loadURL('about:blank');
  2131. w.webContents.executeJavaScript('window.moveTo(100, 100)', true);
  2132. const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle];
  2133. const { width, height } = w.getBounds();
  2134. expect(rect).to.deep.equal({
  2135. x: 100,
  2136. y: 100,
  2137. width,
  2138. height
  2139. });
  2140. await new Promise(setImmediate);
  2141. expect(w.getBounds().x).to.equal(100);
  2142. expect(w.getBounds().y).to.equal(100);
  2143. });
  2144. it('emits when resizeTo is called', async () => {
  2145. const w = new BrowserWindow({ show: false });
  2146. w.loadURL('about:blank');
  2147. w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
  2148. const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle];
  2149. const { x, y } = w.getBounds();
  2150. expect(rect).to.deep.equal({
  2151. x,
  2152. y,
  2153. width: 100,
  2154. height: 100
  2155. });
  2156. await new Promise(setImmediate);
  2157. expect({
  2158. width: w.getBounds().width,
  2159. height: w.getBounds().height
  2160. }).to.deep.equal(process.platform === 'win32' ? {
  2161. // The width is reported as being larger on Windows? I'm not sure why
  2162. // this is.
  2163. width: 136,
  2164. height: 100
  2165. } : {
  2166. width: 100,
  2167. height: 100
  2168. });
  2169. });
  2170. it('does not change window bounds if cancelled', async () => {
  2171. const w = new BrowserWindow({ show: false });
  2172. const { width, height } = w.getBounds();
  2173. w.loadURL('about:blank');
  2174. w.webContents.once('content-bounds-updated', e => e.preventDefault());
  2175. await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
  2176. await new Promise(setImmediate);
  2177. expect(w.getBounds().width).to.equal(width);
  2178. expect(w.getBounds().height).to.equal(height);
  2179. });
  2180. });
  2181. });