api-web-contents-spec.ts 91 KB

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