api-web-contents-spec.ts 91 KB

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