api-web-contents-spec.ts 87 KB

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