api-web-contents-spec.ts 103 KB

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