api-web-contents-spec.ts 86 KB

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