api-web-contents-spec.ts 108 KB

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