api-web-contents-spec.ts 94 KB

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