api-web-contents-spec.ts 86 KB

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