api-web-contents-spec.ts 99 KB

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