api-web-contents-spec.ts 90 KB

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