api-web-contents-spec.ts 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136
  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('focusedFrame api', () => {
  1612. const focusFrame = (frame: Electron.WebFrameMain) => {
  1613. // There has to be a better way to do this...
  1614. return frame.executeJavaScript(`(${() => {
  1615. const input = document.createElement('input');
  1616. document.body.appendChild(input);
  1617. input.onfocus = () => input.remove();
  1618. input.focus();
  1619. }})()`, true);
  1620. };
  1621. it('is null before a url is committed', () => {
  1622. const w = new BrowserWindow({ show: false });
  1623. expect(w.webContents.focusedFrame).to.be.null();
  1624. });
  1625. it('is set when main frame is focused', async () => {
  1626. const w = new BrowserWindow({ show: true });
  1627. await w.loadURL('about:blank');
  1628. w.webContents.focus();
  1629. await waitUntil(() => w.webContents.focusedFrame === w.webContents.mainFrame);
  1630. });
  1631. it('is set to child frame when focused', async () => {
  1632. const w = new BrowserWindow({ show: true });
  1633. await w.loadFile(path.join(fixturesPath, 'sub-frames', 'frame-with-frame-container.html'));
  1634. const childFrame = w.webContents.mainFrame.frames[0];
  1635. await focusFrame(childFrame);
  1636. await waitUntil(() => w.webContents.focusedFrame === childFrame);
  1637. });
  1638. });
  1639. describe('render view deleted events', () => {
  1640. let server: http.Server;
  1641. let serverUrl: string;
  1642. let crossSiteUrl: string;
  1643. before(async () => {
  1644. server = http.createServer((req, res) => {
  1645. const respond = () => {
  1646. if (req.url === '/redirect-cross-site') {
  1647. res.setHeader('Location', `${crossSiteUrl}/redirected`);
  1648. res.statusCode = 302;
  1649. res.end();
  1650. } else if (req.url === '/redirected') {
  1651. res.end('<html><script>window.localStorage</script></html>');
  1652. } else if (req.url === '/first-window-open') {
  1653. res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`);
  1654. } else if (req.url === '/second-window-open') {
  1655. res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>');
  1656. } else {
  1657. res.end();
  1658. }
  1659. };
  1660. setTimeout().then(respond);
  1661. });
  1662. serverUrl = (await listen(server)).url;
  1663. crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
  1664. });
  1665. after(() => {
  1666. server.close();
  1667. });
  1668. afterEach(closeAllWindows);
  1669. it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
  1670. const w = new BrowserWindow({ show: false });
  1671. let currentRenderViewDeletedEmitted = false;
  1672. const renderViewDeletedHandler = () => {
  1673. currentRenderViewDeletedEmitted = true;
  1674. };
  1675. w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
  1676. w.webContents.on('did-finish-load', () => {
  1677. w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
  1678. w.close();
  1679. });
  1680. const destroyed = once(w.webContents, 'destroyed');
  1681. w.loadURL(`${serverUrl}/redirect-cross-site`);
  1682. await destroyed;
  1683. expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted');
  1684. });
  1685. it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
  1686. const parentWindow = new BrowserWindow({ show: false });
  1687. let currentRenderViewDeletedEmitted = false;
  1688. let childWindow: BrowserWindow | null = null;
  1689. const destroyed = once(parentWindow.webContents, 'destroyed');
  1690. const renderViewDeletedHandler = () => {
  1691. currentRenderViewDeletedEmitted = true;
  1692. };
  1693. const childWindowCreated = new Promise<void>((resolve) => {
  1694. app.once('browser-window-created', (event, window) => {
  1695. childWindow = window;
  1696. window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
  1697. resolve();
  1698. });
  1699. });
  1700. parentWindow.loadURL(`${serverUrl}/first-window-open`);
  1701. await childWindowCreated;
  1702. childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
  1703. parentWindow.close();
  1704. await destroyed;
  1705. expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed');
  1706. });
  1707. it('emits current-render-view-deleted if the current RVHs are deleted', async () => {
  1708. const w = new BrowserWindow({ show: false });
  1709. let currentRenderViewDeletedEmitted = false;
  1710. w.webContents.on('current-render-view-deleted' as any, () => {
  1711. currentRenderViewDeletedEmitted = true;
  1712. });
  1713. w.webContents.on('did-finish-load', () => {
  1714. w.close();
  1715. });
  1716. const destroyed = once(w.webContents, 'destroyed');
  1717. w.loadURL(`${serverUrl}/redirect-cross-site`);
  1718. await destroyed;
  1719. expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted');
  1720. });
  1721. it('emits render-view-deleted if any RVHs are deleted', async () => {
  1722. const w = new BrowserWindow({ show: false });
  1723. let rvhDeletedCount = 0;
  1724. w.webContents.on('render-view-deleted' as any, () => {
  1725. rvhDeletedCount++;
  1726. });
  1727. w.webContents.on('did-finish-load', () => {
  1728. w.close();
  1729. });
  1730. const destroyed = once(w.webContents, 'destroyed');
  1731. w.loadURL(`${serverUrl}/redirect-cross-site`);
  1732. await destroyed;
  1733. const expectedRenderViewDeletedEventCount = 1;
  1734. expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times');
  1735. });
  1736. });
  1737. describe('setIgnoreMenuShortcuts(ignore)', () => {
  1738. afterEach(closeAllWindows);
  1739. it('does not throw', () => {
  1740. const w = new BrowserWindow({ show: false });
  1741. expect(() => {
  1742. w.webContents.setIgnoreMenuShortcuts(true);
  1743. w.webContents.setIgnoreMenuShortcuts(false);
  1744. }).to.not.throw();
  1745. });
  1746. });
  1747. const crashPrefs = [
  1748. {
  1749. nodeIntegration: true
  1750. },
  1751. {
  1752. sandbox: true
  1753. }
  1754. ];
  1755. const nicePrefs = (o: any) => {
  1756. let s = '';
  1757. for (const key of Object.keys(o)) {
  1758. s += `${key}=${o[key]}, `;
  1759. }
  1760. return `(${s.slice(0, s.length - 2)})`;
  1761. };
  1762. for (const prefs of crashPrefs) {
  1763. describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => {
  1764. let w: BrowserWindow;
  1765. beforeEach(async () => {
  1766. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  1767. await w.loadURL('about:blank');
  1768. });
  1769. afterEach(closeAllWindows);
  1770. it('isCrashed() is false by default', () => {
  1771. expect(w.webContents.isCrashed()).to.equal(false);
  1772. });
  1773. it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => {
  1774. expect(w.webContents.isCrashed()).to.equal(false);
  1775. const crashEvent = once(w.webContents, 'render-process-gone') as Promise<[any, Electron.RenderProcessGoneDetails]>;
  1776. w.webContents.forcefullyCrashRenderer();
  1777. const [, details] = await crashEvent;
  1778. expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed');
  1779. expect(w.webContents.isCrashed()).to.equal(true);
  1780. });
  1781. it('a crashed process is recoverable with reload()', async () => {
  1782. expect(w.webContents.isCrashed()).to.equal(false);
  1783. w.webContents.forcefullyCrashRenderer();
  1784. w.webContents.reload();
  1785. expect(w.webContents.isCrashed()).to.equal(false);
  1786. });
  1787. });
  1788. }
  1789. // Destroying webContents in its event listener is going to crash when
  1790. // Electron is built in Debug mode.
  1791. describe('destroy()', () => {
  1792. let server: http.Server;
  1793. let serverUrl: string;
  1794. before((done) => {
  1795. server = http.createServer((request, response) => {
  1796. switch (request.url) {
  1797. case '/net-error':
  1798. response.destroy();
  1799. break;
  1800. case '/200':
  1801. response.end();
  1802. break;
  1803. default:
  1804. done(new Error('unsupported endpoint'));
  1805. }
  1806. });
  1807. listen(server).then(({ url }) => {
  1808. serverUrl = url;
  1809. done();
  1810. });
  1811. });
  1812. after(() => {
  1813. server.close();
  1814. });
  1815. const events = [
  1816. { name: 'did-start-loading', url: '/200' },
  1817. { name: 'dom-ready', url: '/200' },
  1818. { name: 'did-stop-loading', url: '/200' },
  1819. { name: 'did-finish-load', url: '/200' },
  1820. // FIXME: Multiple Emit calls inside an observer assume that object
  1821. // will be alive till end of the observer. Synchronous `destroy` api
  1822. // violates this contract and crashes.
  1823. { name: 'did-frame-finish-load', url: '/200' },
  1824. { name: 'did-fail-load', url: '/net-error' }
  1825. ];
  1826. for (const e of events) {
  1827. it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () {
  1828. // This test is flaky on Windows CI and we don't know why, but the
  1829. // purpose of this test is to make sure Electron does not crash so it
  1830. // is fine to retry this test for a few times.
  1831. this.retries(3);
  1832. const contents = (webContents as typeof ElectronInternal.WebContents).create();
  1833. const originalEmit = contents.emit.bind(contents);
  1834. contents.emit = (...args) => { return originalEmit(...args); };
  1835. contents.once(e.name as any, () => contents.destroy());
  1836. const destroyed = once(contents, 'destroyed');
  1837. contents.loadURL(serverUrl + e.url);
  1838. await destroyed;
  1839. });
  1840. }
  1841. });
  1842. describe('did-change-theme-color event', () => {
  1843. afterEach(closeAllWindows);
  1844. it('is triggered with correct theme color', (done) => {
  1845. const w = new BrowserWindow({ show: true });
  1846. let count = 0;
  1847. w.webContents.on('did-change-theme-color', (e, color) => {
  1848. try {
  1849. if (count === 0) {
  1850. count += 1;
  1851. expect(color).to.equal('#FFEEDD');
  1852. w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  1853. } else if (count === 1) {
  1854. expect(color).to.be.null();
  1855. done();
  1856. }
  1857. } catch (e) {
  1858. done(e);
  1859. }
  1860. });
  1861. w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html'));
  1862. });
  1863. });
  1864. describe('console-message event', () => {
  1865. afterEach(closeAllWindows);
  1866. it('is triggered with correct log message', (done) => {
  1867. const w = new BrowserWindow({ show: true });
  1868. w.webContents.on('console-message', (e) => {
  1869. // Don't just assert as Chromium might emit other logs that we should ignore.
  1870. if (e.message === 'a') {
  1871. done();
  1872. }
  1873. });
  1874. w.loadFile(path.join(fixturesPath, 'pages', 'a.html'));
  1875. });
  1876. });
  1877. describe('ipc-message event', () => {
  1878. afterEach(closeAllWindows);
  1879. it('emits when the renderer process sends an asynchronous message', async () => {
  1880. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1881. await w.webContents.loadURL('about:blank');
  1882. w.webContents.executeJavaScript(`
  1883. require('electron').ipcRenderer.send('message', 'Hello World!')
  1884. `);
  1885. const [, channel, message] = await once(w.webContents, 'ipc-message');
  1886. expect(channel).to.equal('message');
  1887. expect(message).to.equal('Hello World!');
  1888. });
  1889. });
  1890. describe('ipc-message-sync event', () => {
  1891. afterEach(closeAllWindows);
  1892. it('emits when the renderer process sends a synchronous message', async () => {
  1893. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1894. await w.webContents.loadURL('about:blank');
  1895. const promise: Promise<[string, string]> = new Promise(resolve => {
  1896. w.webContents.once('ipc-message-sync', (event, channel, arg) => {
  1897. event.returnValue = 'foobar';
  1898. resolve([channel, arg]);
  1899. });
  1900. });
  1901. const result = await w.webContents.executeJavaScript(`
  1902. require('electron').ipcRenderer.sendSync('message', 'Hello World!')
  1903. `);
  1904. const [channel, message] = await promise;
  1905. expect(channel).to.equal('message');
  1906. expect(message).to.equal('Hello World!');
  1907. expect(result).to.equal('foobar');
  1908. });
  1909. });
  1910. describe('referrer', () => {
  1911. afterEach(closeAllWindows);
  1912. it('propagates referrer information to new target=_blank windows', (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('<a id="a" href="/should_have_referrer" target="_blank">link</a>');
  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('a.click()');
  1936. });
  1937. w.loadURL(url);
  1938. });
  1939. });
  1940. it('propagates referrer information to windows opened with window.open', (done) => {
  1941. const w = new BrowserWindow({ show: false });
  1942. const server = http.createServer((req, res) => {
  1943. if (req.url === '/should_have_referrer') {
  1944. try {
  1945. expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
  1946. return done();
  1947. } catch (e) {
  1948. return done(e);
  1949. }
  1950. }
  1951. res.end('');
  1952. });
  1953. defer(() => {
  1954. server.close();
  1955. });
  1956. listen(server).then(({ url }) => {
  1957. w.webContents.once('did-finish-load', () => {
  1958. w.webContents.setWindowOpenHandler(details => {
  1959. expect(details.referrer.url).to.equal(url + '/');
  1960. expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
  1961. return { action: 'allow' };
  1962. });
  1963. w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")');
  1964. });
  1965. w.loadURL(url);
  1966. });
  1967. });
  1968. });
  1969. describe('webframe messages in sandboxed contents', () => {
  1970. afterEach(closeAllWindows);
  1971. it('responds to executeJavaScript', async () => {
  1972. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1973. await w.loadURL('about:blank');
  1974. const result = await w.webContents.executeJavaScript('37 + 5');
  1975. expect(result).to.equal(42);
  1976. });
  1977. });
  1978. describe('preload-error event', () => {
  1979. afterEach(closeAllWindows);
  1980. const generateSpecs = (description: string, sandbox: boolean) => {
  1981. describe(description, () => {
  1982. it('is triggered when unhandled exception is thrown', async () => {
  1983. const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js');
  1984. const w = new BrowserWindow({
  1985. show: false,
  1986. webPreferences: {
  1987. sandbox,
  1988. preload
  1989. }
  1990. });
  1991. const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
  1992. w.loadURL('about:blank');
  1993. const [, preloadPath, error] = await promise;
  1994. expect(preloadPath).to.equal(preload);
  1995. expect(error.message).to.equal('Hello World!');
  1996. });
  1997. it('is triggered on syntax errors', async () => {
  1998. const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js');
  1999. const w = new BrowserWindow({
  2000. show: false,
  2001. webPreferences: {
  2002. sandbox,
  2003. preload
  2004. }
  2005. });
  2006. const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
  2007. w.loadURL('about:blank');
  2008. const [, preloadPath, error] = await promise;
  2009. expect(preloadPath).to.equal(preload);
  2010. expect(error.message).to.equal('foobar is not defined');
  2011. });
  2012. it('is triggered when preload script loading fails', async () => {
  2013. const preload = path.join(fixturesPath, 'module', 'preload-invalid.js');
  2014. const w = new BrowserWindow({
  2015. show: false,
  2016. webPreferences: {
  2017. sandbox,
  2018. preload
  2019. }
  2020. });
  2021. const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
  2022. w.loadURL('about:blank');
  2023. const [, preloadPath, error] = await promise;
  2024. expect(preloadPath).to.equal(preload);
  2025. expect(error.message).to.contain('preload-invalid.js');
  2026. });
  2027. });
  2028. };
  2029. generateSpecs('without sandbox', false);
  2030. generateSpecs('with sandbox', true);
  2031. });
  2032. describe('takeHeapSnapshot()', () => {
  2033. afterEach(closeAllWindows);
  2034. it('works with sandboxed renderers', async () => {
  2035. const w = new BrowserWindow({
  2036. show: false,
  2037. webPreferences: {
  2038. sandbox: true
  2039. }
  2040. });
  2041. await w.loadURL('about:blank');
  2042. const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
  2043. const cleanup = () => {
  2044. try {
  2045. fs.unlinkSync(filePath);
  2046. } catch {
  2047. // ignore error
  2048. }
  2049. };
  2050. try {
  2051. await w.webContents.takeHeapSnapshot(filePath);
  2052. const stats = fs.statSync(filePath);
  2053. expect(stats.size).not.to.be.equal(0);
  2054. } finally {
  2055. cleanup();
  2056. }
  2057. });
  2058. it('fails with invalid file path', async () => {
  2059. const w = new BrowserWindow({
  2060. show: false,
  2061. webPreferences: {
  2062. sandbox: true
  2063. }
  2064. });
  2065. await w.loadURL('about:blank');
  2066. const badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path');
  2067. const promise = w.webContents.takeHeapSnapshot(badPath);
  2068. return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`);
  2069. });
  2070. it('fails with invalid render process', async () => {
  2071. const w = new BrowserWindow({
  2072. show: false,
  2073. webPreferences: {
  2074. sandbox: true
  2075. }
  2076. });
  2077. const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
  2078. w.webContents.destroy();
  2079. const promise = w.webContents.takeHeapSnapshot(filePath);
  2080. return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame');
  2081. });
  2082. });
  2083. describe('setBackgroundThrottling()', () => {
  2084. afterEach(closeAllWindows);
  2085. it('does not crash when allowing', () => {
  2086. const w = new BrowserWindow({ show: false });
  2087. w.webContents.setBackgroundThrottling(true);
  2088. });
  2089. it('does not crash when called via BrowserWindow', () => {
  2090. const w = new BrowserWindow({ show: false });
  2091. w.setBackgroundThrottling(true);
  2092. });
  2093. it('does not crash when disallowing', () => {
  2094. const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } });
  2095. w.webContents.setBackgroundThrottling(false);
  2096. });
  2097. });
  2098. describe('getBackgroundThrottling()', () => {
  2099. afterEach(closeAllWindows);
  2100. it('works via getter', () => {
  2101. const w = new BrowserWindow({ show: false });
  2102. w.webContents.setBackgroundThrottling(false);
  2103. expect(w.webContents.getBackgroundThrottling()).to.equal(false);
  2104. w.webContents.setBackgroundThrottling(true);
  2105. expect(w.webContents.getBackgroundThrottling()).to.equal(true);
  2106. });
  2107. it('works via property', () => {
  2108. const w = new BrowserWindow({ show: false });
  2109. w.webContents.backgroundThrottling = false;
  2110. expect(w.webContents.backgroundThrottling).to.equal(false);
  2111. w.webContents.backgroundThrottling = true;
  2112. expect(w.webContents.backgroundThrottling).to.equal(true);
  2113. });
  2114. it('works via BrowserWindow', () => {
  2115. const w = new BrowserWindow({ show: false });
  2116. w.setBackgroundThrottling(false);
  2117. expect(w.getBackgroundThrottling()).to.equal(false);
  2118. w.setBackgroundThrottling(true);
  2119. expect(w.getBackgroundThrottling()).to.equal(true);
  2120. });
  2121. });
  2122. ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => {
  2123. afterEach(closeAllWindows);
  2124. it('can get printer list', async () => {
  2125. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  2126. await w.loadURL('about:blank');
  2127. const printers = await w.webContents.getPrintersAsync();
  2128. expect(printers).to.be.an('array');
  2129. });
  2130. });
  2131. ifdescribe(features.isPrintingEnabled())('printToPDF()', () => {
  2132. const readPDF = async (data: any) => {
  2133. const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'e-spec-printtopdf-'));
  2134. const pdfPath = path.resolve(tmpDir, 'test.pdf');
  2135. await fs.promises.writeFile(pdfPath, data);
  2136. const pdfReaderPath = path.resolve(fixturesPath, 'api', 'pdf-reader.mjs');
  2137. const result = cp.spawn(process.execPath, [pdfReaderPath, pdfPath], {
  2138. stdio: 'pipe'
  2139. });
  2140. const stdout: Buffer[] = [];
  2141. const stderr: Buffer[] = [];
  2142. result.stdout.on('data', (chunk) => stdout.push(chunk));
  2143. result.stderr.on('data', (chunk) => stderr.push(chunk));
  2144. const [code, signal] = await new Promise<[number | null, NodeJS.Signals | null]>((resolve) => {
  2145. result.on('close', (code, signal) => {
  2146. resolve([code, signal]);
  2147. });
  2148. });
  2149. await fs.promises.rm(tmpDir, { force: true, recursive: true });
  2150. if (code !== 0) {
  2151. const errMsg = Buffer.concat(stderr).toString().trim();
  2152. console.error(`Error parsing PDF file, exit code was ${code}; signal was ${signal}, error: ${errMsg}`);
  2153. }
  2154. return JSON.parse(Buffer.concat(stdout).toString().trim());
  2155. };
  2156. let w: BrowserWindow;
  2157. const containsText = (items: any[], text: RegExp) => {
  2158. return items.some(({ str }: { str: string }) => str.match(text));
  2159. };
  2160. beforeEach(() => {
  2161. w = new BrowserWindow({
  2162. show: false,
  2163. webPreferences: {
  2164. sandbox: true
  2165. }
  2166. });
  2167. });
  2168. afterEach(closeAllWindows);
  2169. it('rejects on incorrectly typed parameters', async () => {
  2170. const badTypes = {
  2171. landscape: [],
  2172. displayHeaderFooter: '123',
  2173. printBackground: 2,
  2174. scale: 'not-a-number',
  2175. pageSize: 'IAmAPageSize',
  2176. margins: 'terrible',
  2177. pageRanges: { oops: 'im-not-the-right-key' },
  2178. headerTemplate: [1, 2, 3],
  2179. footerTemplate: [4, 5, 6],
  2180. preferCSSPageSize: 'no',
  2181. generateTaggedPDF: 'wtf',
  2182. generateDocumentOutline: [7, 8, 9]
  2183. };
  2184. await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
  2185. // These will hard crash in Chromium unless we type-check
  2186. for (const [key, value] of Object.entries(badTypes)) {
  2187. const param = { [key]: value };
  2188. await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected();
  2189. }
  2190. });
  2191. it('rejects when margins exceed physical page size', async () => {
  2192. await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
  2193. await expect(w.webContents.printToPDF({
  2194. pageSize: 'Letter',
  2195. margins: {
  2196. top: 100,
  2197. bottom: 100,
  2198. left: 5,
  2199. right: 5
  2200. }
  2201. })).to.eventually.be.rejectedWith('margins must be less than or equal to pageSize');
  2202. });
  2203. it('does not crash when called multiple times in parallel', async () => {
  2204. await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
  2205. const promises = [];
  2206. for (let i = 0; i < 3; i++) {
  2207. promises.push(w.webContents.printToPDF({}));
  2208. }
  2209. const results = await Promise.all(promises);
  2210. for (const data of results) {
  2211. expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
  2212. }
  2213. });
  2214. it('does not crash when called multiple times in sequence', async () => {
  2215. await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
  2216. const results = [];
  2217. for (let i = 0; i < 3; i++) {
  2218. const result = await w.webContents.printToPDF({});
  2219. results.push(result);
  2220. }
  2221. for (const data of results) {
  2222. expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
  2223. }
  2224. });
  2225. it('can print a PDF with default settings', async () => {
  2226. await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
  2227. const data = await w.webContents.printToPDF({});
  2228. expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
  2229. });
  2230. type PageSizeString = Exclude<Required<Electron.PrintToPDFOptions>['pageSize'], Electron.Size>;
  2231. it('with custom page sizes', async () => {
  2232. const paperFormats: Record<PageSizeString, ElectronInternal.PageSize> = {
  2233. Letter: { width: 8.5, height: 11 },
  2234. Legal: { width: 8.5, height: 14 },
  2235. Tabloid: { width: 11, height: 17 },
  2236. Ledger: { width: 17, height: 11 },
  2237. A0: { width: 33.1, height: 46.8 },
  2238. A1: { width: 23.4, height: 33.1 },
  2239. A2: { width: 16.54, height: 23.4 },
  2240. A3: { width: 11.7, height: 16.54 },
  2241. A4: { width: 8.27, height: 11.7 },
  2242. A5: { width: 5.83, height: 8.27 },
  2243. A6: { width: 4.13, height: 5.83 }
  2244. };
  2245. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
  2246. for (const format of Object.keys(paperFormats) as PageSizeString[]) {
  2247. const data = await w.webContents.printToPDF({ pageSize: format });
  2248. const pdfInfo = await readPDF(data);
  2249. // page.view is [top, left, width, height].
  2250. const width = pdfInfo.view[2] / 72;
  2251. const height = pdfInfo.view[3] / 72;
  2252. const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon;
  2253. expect(approxEq(width, paperFormats[format].width)).to.be.true();
  2254. expect(approxEq(height, paperFormats[format].height)).to.be.true();
  2255. }
  2256. });
  2257. it('with custom header and footer', async () => {
  2258. await w.loadFile(path.join(fixturesPath, 'api', 'print-to-pdf-small.html'));
  2259. const data = await w.webContents.printToPDF({
  2260. displayHeaderFooter: true,
  2261. headerTemplate: '<div>I\'m a PDF header</div>',
  2262. footerTemplate: '<div>I\'m a PDF footer</div>'
  2263. });
  2264. const pdfInfo = await readPDF(data);
  2265. expect(containsText(pdfInfo.textContent, /I'm a PDF header/)).to.be.true();
  2266. expect(containsText(pdfInfo.textContent, /I'm a PDF footer/)).to.be.true();
  2267. });
  2268. it('in landscape mode', async () => {
  2269. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
  2270. const data = await w.webContents.printToPDF({ landscape: true });
  2271. const pdfInfo = await readPDF(data);
  2272. // page.view is [top, left, width, height].
  2273. const width = pdfInfo.view[2];
  2274. const height = pdfInfo.view[3];
  2275. expect(width).to.be.greaterThan(height);
  2276. });
  2277. it('with custom page ranges', async () => {
  2278. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html'));
  2279. const data = await w.webContents.printToPDF({
  2280. pageRanges: '1-3',
  2281. landscape: true
  2282. });
  2283. const pdfInfo = await readPDF(data);
  2284. // Check that correct # of pages are rendered.
  2285. expect(pdfInfo.numPages).to.equal(3);
  2286. });
  2287. it('does not tag PDFs by default', async () => {
  2288. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
  2289. const data = await w.webContents.printToPDF({});
  2290. const pdfInfo = await readPDF(data);
  2291. expect(pdfInfo.markInfo).to.be.null();
  2292. });
  2293. it('can generate tag data for PDFs', async () => {
  2294. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
  2295. const data = await w.webContents.printToPDF({ generateTaggedPDF: true });
  2296. const pdfInfo = await readPDF(data);
  2297. expect(pdfInfo.markInfo).to.deep.equal({
  2298. Marked: true,
  2299. UserProperties: false,
  2300. Suspects: false
  2301. });
  2302. });
  2303. it('from an existing pdf document', async () => {
  2304. const pdfPath = path.join(fixturesPath, 'cat.pdf');
  2305. const readyToPrint = once(w.webContents, '-pdf-ready-to-print');
  2306. await w.loadFile(pdfPath);
  2307. await readyToPrint;
  2308. const data = await w.webContents.printToPDF({});
  2309. const pdfInfo = await readPDF(data);
  2310. expect(pdfInfo.numPages).to.equal(2);
  2311. expect(containsText(pdfInfo.textContent, /Cat: The Ideal Pet/)).to.be.true();
  2312. });
  2313. it('from an existing pdf document in a WebView', async () => {
  2314. const win = new BrowserWindow({
  2315. show: false,
  2316. webPreferences: {
  2317. webviewTag: true
  2318. }
  2319. });
  2320. await win.loadURL('about:blank');
  2321. const webContentsCreated = once(app, 'web-contents-created') as Promise<[any, WebContents]>;
  2322. const src = url.format({
  2323. pathname: `${fixturesPath.replaceAll('\\', '/')}/cat.pdf`,
  2324. protocol: 'file',
  2325. slashes: true
  2326. });
  2327. await win.webContents.executeJavaScript(`
  2328. new Promise((resolve, reject) => {
  2329. const webview = new WebView()
  2330. webview.setAttribute('src', '${src}')
  2331. document.body.appendChild(webview)
  2332. webview.addEventListener('did-finish-load', () => {
  2333. resolve()
  2334. })
  2335. })
  2336. `);
  2337. const [, webContents] = await webContentsCreated;
  2338. await once(webContents, '-pdf-ready-to-print');
  2339. const data = await webContents.printToPDF({});
  2340. const pdfInfo = await readPDF(data);
  2341. expect(pdfInfo.numPages).to.equal(2);
  2342. expect(containsText(pdfInfo.textContent, /Cat: The Ideal Pet/)).to.be.true();
  2343. });
  2344. });
  2345. describe('PictureInPicture video', () => {
  2346. afterEach(closeAllWindows);
  2347. it('works as expected', async function () {
  2348. const w = new BrowserWindow({ webPreferences: { sandbox: true } });
  2349. // TODO(codebytere): figure out why this workaround is needed and remove.
  2350. // It is not germane to the actual test.
  2351. await w.loadFile(path.join(fixturesPath, 'blank.html'));
  2352. await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html'));
  2353. await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true);
  2354. const result = await w.webContents.executeJavaScript('runTest(true)', true);
  2355. expect(result).to.be.true();
  2356. });
  2357. });
  2358. describe('Shared Workers', () => {
  2359. afterEach(closeAllWindows);
  2360. it('can get multiple shared workers', async () => {
  2361. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  2362. const ready = once(ipcMain, 'ready');
  2363. w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
  2364. await ready;
  2365. const sharedWorkers = w.webContents.getAllSharedWorkers();
  2366. expect(sharedWorkers).to.have.lengthOf(2);
  2367. expect(sharedWorkers[0].url).to.contain('shared-worker');
  2368. expect(sharedWorkers[1].url).to.contain('shared-worker');
  2369. });
  2370. it('can inspect a specific shared worker', async () => {
  2371. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  2372. const ready = once(ipcMain, 'ready');
  2373. w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
  2374. await ready;
  2375. const sharedWorkers = w.webContents.getAllSharedWorkers();
  2376. const devtoolsOpened = once(w.webContents, 'devtools-opened');
  2377. w.webContents.inspectSharedWorkerById(sharedWorkers[0].id);
  2378. await devtoolsOpened;
  2379. const devtoolsClosed = once(w.webContents, 'devtools-closed');
  2380. w.webContents.closeDevTools();
  2381. await devtoolsClosed;
  2382. });
  2383. });
  2384. describe('login event', () => {
  2385. afterEach(closeAllWindows);
  2386. let server: http.Server;
  2387. let serverUrl: string;
  2388. let serverPort: number;
  2389. let proxyServer: http.Server;
  2390. let proxyServerPort: number;
  2391. before(async () => {
  2392. server = http.createServer((request, response) => {
  2393. if (request.url === '/no-auth') {
  2394. return response.end('ok');
  2395. }
  2396. if (request.headers.authorization) {
  2397. response.writeHead(200, { 'Content-type': 'text/plain' });
  2398. return response.end(request.headers.authorization);
  2399. }
  2400. response
  2401. .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
  2402. .end('401');
  2403. });
  2404. ({ port: serverPort, url: serverUrl } = await listen(server));
  2405. });
  2406. before(async () => {
  2407. proxyServer = http.createServer((request, response) => {
  2408. if (request.headers['proxy-authorization']) {
  2409. response.writeHead(200, { 'Content-type': 'text/plain' });
  2410. return response.end(request.headers['proxy-authorization']);
  2411. }
  2412. response
  2413. .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' })
  2414. .end();
  2415. });
  2416. proxyServerPort = (await listen(proxyServer)).port;
  2417. });
  2418. afterEach(async () => {
  2419. await session.defaultSession.clearAuthCache();
  2420. });
  2421. after(() => {
  2422. server.close();
  2423. proxyServer.close();
  2424. });
  2425. it('is emitted when navigating', async () => {
  2426. const [user, pass] = ['user', 'pass'];
  2427. const w = new BrowserWindow({ show: false });
  2428. let eventRequest: any;
  2429. let eventAuthInfo: any;
  2430. w.webContents.on('login', (event, request, authInfo, cb) => {
  2431. eventRequest = request;
  2432. eventAuthInfo = authInfo;
  2433. event.preventDefault();
  2434. cb(user, pass);
  2435. });
  2436. await w.loadURL(serverUrl);
  2437. const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
  2438. expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
  2439. expect(eventRequest.url).to.equal(serverUrl + '/');
  2440. expect(eventAuthInfo.isProxy).to.be.false();
  2441. expect(eventAuthInfo.scheme).to.equal('basic');
  2442. expect(eventAuthInfo.host).to.equal('127.0.0.1');
  2443. expect(eventAuthInfo.port).to.equal(serverPort);
  2444. expect(eventAuthInfo.realm).to.equal('Foo');
  2445. });
  2446. it('is emitted when a proxy requests authorization', async () => {
  2447. const customSession = session.fromPartition(`${Math.random()}`);
  2448. await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' });
  2449. const [user, pass] = ['user', 'pass'];
  2450. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  2451. let eventRequest: any;
  2452. let eventAuthInfo: any;
  2453. w.webContents.on('login', (event, request, authInfo, cb) => {
  2454. eventRequest = request;
  2455. eventAuthInfo = authInfo;
  2456. event.preventDefault();
  2457. cb(user, pass);
  2458. });
  2459. await w.loadURL(`${serverUrl}/no-auth`);
  2460. const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
  2461. expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
  2462. expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`);
  2463. expect(eventAuthInfo.isProxy).to.be.true();
  2464. expect(eventAuthInfo.scheme).to.equal('basic');
  2465. expect(eventAuthInfo.host).to.equal('127.0.0.1');
  2466. expect(eventAuthInfo.port).to.equal(proxyServerPort);
  2467. expect(eventAuthInfo.realm).to.equal('Foo');
  2468. });
  2469. it('cancels authentication when callback is called with no arguments', async () => {
  2470. const w = new BrowserWindow({ show: false });
  2471. w.webContents.on('login', (event, request, authInfo, cb) => {
  2472. event.preventDefault();
  2473. cb();
  2474. });
  2475. await w.loadURL(serverUrl);
  2476. const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
  2477. expect(body).to.equal('401');
  2478. });
  2479. });
  2480. describe('page-title-updated event', () => {
  2481. afterEach(closeAllWindows);
  2482. it('is emitted with a full title for pages with no navigation', async () => {
  2483. const bw = new BrowserWindow({ show: false });
  2484. await bw.loadURL('about:blank');
  2485. bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null');
  2486. const [, child] = await once(app, 'web-contents-created') as [any, WebContents];
  2487. bw.webContents.executeJavaScript('child.document.title = "new title"');
  2488. const [, title] = await once(child, 'page-title-updated') as [any, string];
  2489. expect(title).to.equal('new title');
  2490. });
  2491. });
  2492. describe('context-menu event', () => {
  2493. afterEach(closeAllWindows);
  2494. it('emits when right-clicked in page', async () => {
  2495. const w = new BrowserWindow({ show: false });
  2496. await w.loadFile(path.join(fixturesPath, 'pages', 'base-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 opts = { x: 0, y: 0, button: 'right' as const };
  2500. w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' });
  2501. w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' });
  2502. const [, params] = await promise;
  2503. expect(params.pageURL).to.equal(w.webContents.getURL());
  2504. expect(params.frame).to.be.an('object');
  2505. expect(params.x).to.be.a('number');
  2506. expect(params.y).to.be.a('number');
  2507. });
  2508. // Skipping due to lack of native click support.
  2509. it.skip('emits the correct number of times when right-clicked in page', async () => {
  2510. const w = new BrowserWindow({ show: true });
  2511. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  2512. let contextMenuEmitCount = 0;
  2513. w.webContents.on('context-menu', () => {
  2514. contextMenuEmitCount++;
  2515. });
  2516. // TODO(samuelmaddock): Perform native right-click. We've tried then
  2517. // dropped robotjs and nutjs so for now this is a manual test.
  2518. await once(w.webContents, 'context-menu');
  2519. await setTimeout(100);
  2520. expect(contextMenuEmitCount).to.equal(1);
  2521. });
  2522. it('emits when right-clicked in page in a draggable region', async () => {
  2523. const w = new BrowserWindow({ show: false });
  2524. if (process.platform === 'win32') {
  2525. w.on('system-context-menu', (event) => { event.preventDefault(); });
  2526. }
  2527. await w.loadFile(path.join(fixturesPath, 'pages', 'draggable-page.html'));
  2528. const promise = once(w.webContents, 'context-menu') as Promise<[any, Electron.ContextMenuParams]>;
  2529. // Simulate right-click to create context-menu event.
  2530. const midPoint = w.getBounds().width / 2;
  2531. const opts = { x: midPoint, y: midPoint, button: 'right' as const };
  2532. w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' });
  2533. w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' });
  2534. const [, params] = await promise;
  2535. expect(params.pageURL).to.equal(w.webContents.getURL());
  2536. expect(params.frame).to.be.an('object');
  2537. expect(params.x).to.be.a('number');
  2538. expect(params.y).to.be.a('number');
  2539. });
  2540. it('emits when right clicked in a WebContentsView', async () => {
  2541. const w = new BaseWindow({ show: false });
  2542. const mainView = new WebContentsView({
  2543. webPreferences: {
  2544. preload: path.join(__dirname, 'preload.js')
  2545. }
  2546. });
  2547. const draggablePage = path.join(fixturesPath, 'pages', 'draggable-page.html');
  2548. await mainView.webContents.loadFile(draggablePage);
  2549. w.contentView.addChildView(mainView);
  2550. const { width, height } = w.getContentBounds();
  2551. mainView.setBounds({ x: 0, y: 0, width, height });
  2552. const promise = once(mainView.webContents, 'context-menu') as Promise<[any, Electron.ContextMenuParams]>;
  2553. // Simulate right-click to create context-menu event.
  2554. const opts = { x: 0, y: 0, button: 'right' as const };
  2555. mainView.webContents.sendInputEvent({ ...opts, type: 'mouseDown' });
  2556. mainView.webContents.sendInputEvent({ ...opts, type: 'mouseUp' });
  2557. const [, params] = await promise;
  2558. expect(params.pageURL).to.equal(mainView.webContents.getURL());
  2559. expect(params.frame).to.be.an('object');
  2560. expect(params.x).to.be.a('number');
  2561. expect(params.y).to.be.a('number');
  2562. });
  2563. it('emits when right clicked in a BrowserWindow with vibrancy', async () => {
  2564. const w = new BrowserWindow({ show: false, vibrancy: 'titlebar' });
  2565. await w.loadFile(path.join(fixturesPath, 'pages', 'draggable-page.html'));
  2566. const promise = once(w.webContents, 'context-menu') as Promise<[any, Electron.ContextMenuParams]>;
  2567. // Simulate right-click to create context-menu event.
  2568. const opts = { x: 0, y: 0, button: 'right' as const };
  2569. w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' });
  2570. w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' });
  2571. const [, params] = await promise;
  2572. expect(params.pageURL).to.equal(w.webContents.getURL());
  2573. expect(params.frame).to.be.an('object');
  2574. expect(params.x).to.be.a('number');
  2575. expect(params.y).to.be.a('number');
  2576. });
  2577. });
  2578. describe('close() method', () => {
  2579. afterEach(async () => {
  2580. await closeAllWindows();
  2581. await cleanupWebContents();
  2582. });
  2583. it('closes when close() is called', async () => {
  2584. const w = (webContents as typeof ElectronInternal.WebContents).create();
  2585. const destroyed = once(w, 'destroyed');
  2586. w.close();
  2587. await destroyed;
  2588. expect(w.isDestroyed()).to.be.true();
  2589. });
  2590. it('closes when close() is called after loading a page', async () => {
  2591. const w = (webContents as typeof ElectronInternal.WebContents).create();
  2592. await w.loadURL('about:blank');
  2593. const destroyed = once(w, 'destroyed');
  2594. w.close();
  2595. await destroyed;
  2596. expect(w.isDestroyed()).to.be.true();
  2597. });
  2598. it('can be GCed before loading a page', async () => {
  2599. const v8Util = process._linkedBinding('electron_common_v8_util');
  2600. let registry: FinalizationRegistry<unknown> | null = null;
  2601. const cleanedUp = new Promise<number>(resolve => {
  2602. registry = new FinalizationRegistry(resolve as any);
  2603. });
  2604. (() => {
  2605. const w = (webContents as typeof ElectronInternal.WebContents).create();
  2606. registry!.register(w, 42);
  2607. })();
  2608. const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100);
  2609. defer(() => clearInterval(i));
  2610. expect(await cleanedUp).to.equal(42);
  2611. });
  2612. it('causes its parent browserwindow to be closed', async () => {
  2613. const w = new BrowserWindow({ show: false });
  2614. await w.loadURL('about:blank');
  2615. const closed = once(w, 'closed');
  2616. w.webContents.close();
  2617. await closed;
  2618. expect(w.isDestroyed()).to.be.true();
  2619. });
  2620. it('ignores beforeunload if waitForBeforeUnload not specified', async () => {
  2621. const w = (webContents as typeof ElectronInternal.WebContents).create();
  2622. await w.loadURL('about:blank');
  2623. await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
  2624. w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); });
  2625. const destroyed = once(w, 'destroyed');
  2626. w.close();
  2627. await destroyed;
  2628. expect(w.isDestroyed()).to.be.true();
  2629. });
  2630. it('runs beforeunload if waitForBeforeUnload is specified', async () => {
  2631. const w = (webContents as typeof ElectronInternal.WebContents).create();
  2632. await w.loadURL('about:blank');
  2633. await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
  2634. const willPreventUnload = once(w, 'will-prevent-unload');
  2635. w.close({ waitForBeforeUnload: true });
  2636. await willPreventUnload;
  2637. expect(w.isDestroyed()).to.be.false();
  2638. });
  2639. it('overriding beforeunload prevention results in webcontents close', async () => {
  2640. const w = (webContents as typeof ElectronInternal.WebContents).create();
  2641. await w.loadURL('about:blank');
  2642. await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
  2643. w.once('will-prevent-unload', e => e.preventDefault());
  2644. const destroyed = once(w, 'destroyed');
  2645. w.close({ waitForBeforeUnload: true });
  2646. await destroyed;
  2647. expect(w.isDestroyed()).to.be.true();
  2648. });
  2649. });
  2650. describe('content-bounds-updated event', () => {
  2651. afterEach(closeAllWindows);
  2652. it('emits when moveTo is called', async () => {
  2653. const w = new BrowserWindow({ show: false });
  2654. w.loadURL('about:blank');
  2655. w.webContents.executeJavaScript('window.moveTo(50, 50)', true);
  2656. const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle];
  2657. const { width, height } = w.getBounds();
  2658. expect(rect).to.deep.equal({
  2659. x: 50,
  2660. y: 50,
  2661. width,
  2662. height
  2663. });
  2664. await new Promise(setImmediate);
  2665. expect(w.getBounds().x).to.equal(50);
  2666. expect(w.getBounds().y).to.equal(50);
  2667. });
  2668. it('emits when resizeTo is called', async () => {
  2669. const w = new BrowserWindow({ show: false });
  2670. w.loadURL('about:blank');
  2671. w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
  2672. const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle];
  2673. const { x, y } = w.getBounds();
  2674. expect(rect).to.deep.equal({
  2675. x,
  2676. y,
  2677. width: 100,
  2678. height: 100
  2679. });
  2680. await new Promise(setImmediate);
  2681. expect({
  2682. width: w.getBounds().width,
  2683. height: w.getBounds().height
  2684. }).to.deep.equal(process.platform === 'win32'
  2685. ? {
  2686. // The width is reported as being larger on Windows? I'm not sure why
  2687. // this is.
  2688. width: 136,
  2689. height: 100
  2690. }
  2691. : {
  2692. width: 100,
  2693. height: 100
  2694. });
  2695. });
  2696. it('does not change window bounds if cancelled', async () => {
  2697. const w = new BrowserWindow({ show: false });
  2698. const { width, height } = w.getBounds();
  2699. w.loadURL('about:blank');
  2700. w.webContents.once('content-bounds-updated', e => e.preventDefault());
  2701. await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
  2702. await new Promise(setImmediate);
  2703. expect(w.getBounds().width).to.equal(width);
  2704. expect(w.getBounds().height).to.equal(height);
  2705. });
  2706. });
  2707. });