api-web-contents-spec.ts 95 KB

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