api-web-contents-spec.ts 107 KB

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