api-web-contents-spec.ts 112 KB

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