api-web-contents-spec.ts 89 KB

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