api-web-contents-spec.ts 86 KB

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