api-web-contents-spec.ts 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105
  1. import { expect } from 'chai';
  2. import { AddressInfo } from 'net';
  3. import * as path from 'path';
  4. import * as fs from 'fs';
  5. import * as http from 'http';
  6. import { BrowserWindow, ipcMain, webContents, session, WebContents, app, BrowserView } from 'electron/main';
  7. import { emittedOnce } from './events-helpers';
  8. import { closeAllWindows } from './window-helpers';
  9. import { ifdescribe, delay, defer } from './spec-helpers';
  10. const pdfjs = require('pdfjs-dist');
  11. const fixturesPath = path.resolve(__dirname, 'fixtures');
  12. const mainFixturesPath = path.resolve(__dirname, 'fixtures');
  13. const features = process._linkedBinding('electron_common_features');
  14. describe('webContents module', () => {
  15. describe('getAllWebContents() API', () => {
  16. afterEach(closeAllWindows);
  17. it('returns an array of web contents', async () => {
  18. const w = new BrowserWindow({
  19. show: false,
  20. webPreferences: { webviewTag: true }
  21. });
  22. w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html'));
  23. await emittedOnce(w.webContents, 'did-attach-webview');
  24. w.webContents.openDevTools();
  25. await emittedOnce(w.webContents, 'devtools-opened');
  26. const all = webContents.getAllWebContents().sort((a, b) => {
  27. return a.id - b.id;
  28. });
  29. expect(all).to.have.length(3);
  30. expect(all[0].getType()).to.equal('window');
  31. expect(all[all.length - 2].getType()).to.equal('webview');
  32. expect(all[all.length - 1].getType()).to.equal('remote');
  33. });
  34. });
  35. describe('fromId()', () => {
  36. it('returns undefined for an unknown id', () => {
  37. expect(webContents.fromId(12345)).to.be.undefined();
  38. });
  39. });
  40. describe('fromDevToolsTargetId()', () => {
  41. it('returns WebContents for attached DevTools target', async () => {
  42. const w = new BrowserWindow({ show: false });
  43. await w.loadURL('about:blank');
  44. try {
  45. await w.webContents.debugger.attach('1.3');
  46. const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo');
  47. expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents);
  48. } finally {
  49. await w.webContents.debugger.detach();
  50. }
  51. });
  52. it('returns undefined for an unknown id', () => {
  53. expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined();
  54. });
  55. });
  56. describe('will-prevent-unload event', function () {
  57. afterEach(closeAllWindows);
  58. it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => {
  59. const w = new BrowserWindow({ show: false });
  60. w.webContents.once('will-prevent-unload', () => {
  61. expect.fail('should not have fired');
  62. });
  63. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
  64. const wait = emittedOnce(w, 'closed');
  65. w.close();
  66. await wait;
  67. });
  68. it('does not emit if beforeunload returns undefined in a BrowserView', async () => {
  69. const w = new BrowserWindow({ show: false });
  70. const view = new BrowserView();
  71. w.setBrowserView(view);
  72. view.setBounds(w.getBounds());
  73. view.webContents.once('will-prevent-unload', () => {
  74. expect.fail('should not have fired');
  75. });
  76. await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
  77. const wait = emittedOnce(w, 'closed');
  78. w.close();
  79. await wait;
  80. });
  81. it('emits if beforeunload returns false in a BrowserWindow', async () => {
  82. const w = new BrowserWindow({ show: false });
  83. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  84. w.close();
  85. await emittedOnce(w.webContents, 'will-prevent-unload');
  86. });
  87. it('emits if beforeunload returns false in a BrowserView', async () => {
  88. const w = new BrowserWindow({ show: false });
  89. const view = new BrowserView();
  90. w.setBrowserView(view);
  91. view.setBounds(w.getBounds());
  92. await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  93. w.close();
  94. await emittedOnce(view.webContents, 'will-prevent-unload');
  95. });
  96. it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => {
  97. const w = new BrowserWindow({ show: false });
  98. w.webContents.once('will-prevent-unload', event => event.preventDefault());
  99. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  100. const wait = emittedOnce(w, 'closed');
  101. w.close();
  102. await wait;
  103. });
  104. });
  105. describe('webContents.send(channel, args...)', () => {
  106. afterEach(closeAllWindows);
  107. it('throws an error when the channel is missing', () => {
  108. const w = new BrowserWindow({ show: false });
  109. expect(() => {
  110. (w.webContents.send as any)();
  111. }).to.throw('Missing required channel argument');
  112. expect(() => {
  113. w.webContents.send(null as any);
  114. }).to.throw('Missing required channel argument');
  115. });
  116. it('does not block node async APIs when sent before document is ready', (done) => {
  117. // Please reference https://github.com/electron/electron/issues/19368 if
  118. // this test fails.
  119. ipcMain.once('async-node-api-done', () => {
  120. done();
  121. });
  122. const w = new BrowserWindow({
  123. show: false,
  124. webPreferences: {
  125. nodeIntegration: true,
  126. sandbox: false,
  127. contextIsolation: false
  128. }
  129. });
  130. w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html'));
  131. setTimeout(() => {
  132. w.webContents.send('test');
  133. }, 50);
  134. });
  135. });
  136. ifdescribe(features.isPrintingEnabled())('webContents.print()', () => {
  137. let w: BrowserWindow;
  138. beforeEach(() => {
  139. w = new BrowserWindow({ show: false });
  140. });
  141. afterEach(closeAllWindows);
  142. it('throws when invalid settings are passed', () => {
  143. expect(() => {
  144. // @ts-ignore this line is intentionally incorrect
  145. w.webContents.print(true);
  146. }).to.throw('webContents.print(): Invalid print settings specified.');
  147. });
  148. it('throws when an invalid callback is passed', () => {
  149. expect(() => {
  150. // @ts-ignore this line is intentionally incorrect
  151. w.webContents.print({}, true);
  152. }).to.throw('webContents.print(): Invalid optional callback provided.');
  153. });
  154. it('fails when an invalid deviceName is passed', (done) => {
  155. w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => {
  156. expect(success).to.equal(false);
  157. expect(reason).to.match(/Invalid deviceName provided/);
  158. done();
  159. });
  160. });
  161. it('throws when an invalid pageSize is passed', () => {
  162. expect(() => {
  163. // @ts-ignore this line is intentionally incorrect
  164. w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {});
  165. }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize');
  166. });
  167. it('throws when an invalid custom pageSize is passed', () => {
  168. expect(() => {
  169. w.webContents.print({
  170. pageSize: {
  171. width: 100,
  172. height: 200
  173. }
  174. });
  175. }).to.throw('height and width properties must be minimum 352 microns.');
  176. });
  177. it('does not crash with custom margins', () => {
  178. expect(() => {
  179. w.webContents.print({
  180. silent: true,
  181. margins: {
  182. marginType: 'custom',
  183. top: 1,
  184. bottom: 1,
  185. left: 1,
  186. right: 1
  187. }
  188. });
  189. }).to.not.throw();
  190. });
  191. });
  192. describe('webContents.executeJavaScript', () => {
  193. describe('in about:blank', () => {
  194. const expected = 'hello, world!';
  195. const expectedErrorMsg = 'woops!';
  196. const code = `(() => "${expected}")()`;
  197. const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`;
  198. const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`;
  199. const errorTypes = new Set([
  200. Error,
  201. ReferenceError,
  202. EvalError,
  203. RangeError,
  204. SyntaxError,
  205. TypeError,
  206. URIError
  207. ]);
  208. let w: BrowserWindow;
  209. before(async () => {
  210. w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } });
  211. await w.loadURL('about:blank');
  212. });
  213. after(closeAllWindows);
  214. it('resolves the returned promise with the result', async () => {
  215. const result = await w.webContents.executeJavaScript(code);
  216. expect(result).to.equal(expected);
  217. });
  218. it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => {
  219. const result = await w.webContents.executeJavaScript(asyncCode);
  220. expect(result).to.equal(expected);
  221. });
  222. it('rejects the returned promise if an async error is thrown', async () => {
  223. await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg);
  224. });
  225. it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
  226. for (const error of errorTypes) {
  227. await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`))
  228. .to.eventually.be.rejectedWith(error);
  229. }
  230. });
  231. });
  232. describe('on a real page', () => {
  233. let w: BrowserWindow;
  234. beforeEach(() => {
  235. w = new BrowserWindow({ show: false });
  236. });
  237. afterEach(closeAllWindows);
  238. let server: http.Server = null as unknown as http.Server;
  239. let serverUrl: string = null as unknown as string;
  240. before((done) => {
  241. server = http.createServer((request, response) => {
  242. response.end();
  243. }).listen(0, '127.0.0.1', () => {
  244. serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  245. done();
  246. });
  247. });
  248. after(() => {
  249. server.close();
  250. });
  251. it('works after page load and during subframe load', async () => {
  252. await w.loadURL(serverUrl);
  253. // initiate a sub-frame load, then try and execute script during it
  254. await w.webContents.executeJavaScript(`
  255. var iframe = document.createElement('iframe')
  256. iframe.src = '${serverUrl}/slow'
  257. document.body.appendChild(iframe)
  258. null // don't return the iframe
  259. `);
  260. await w.webContents.executeJavaScript('console.log(\'hello\')');
  261. });
  262. it('executes after page load', async () => {
  263. const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()');
  264. w.loadURL(serverUrl);
  265. const result = await executeJavaScript;
  266. expect(result).to.equal('test');
  267. });
  268. });
  269. });
  270. describe('webContents.executeJavaScriptInIsolatedWorld', () => {
  271. let w: BrowserWindow;
  272. before(async () => {
  273. w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } });
  274. await w.loadURL('about:blank');
  275. });
  276. it('resolves the returned promise with the result', async () => {
  277. await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]);
  278. const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]);
  279. const mainWorldResult = await w.webContents.executeJavaScript('window.X');
  280. expect(isolatedResult).to.equal(123);
  281. expect(mainWorldResult).to.equal(undefined);
  282. });
  283. });
  284. describe('loadURL() promise API', () => {
  285. let w: BrowserWindow;
  286. beforeEach(async () => {
  287. w = new BrowserWindow({ show: false });
  288. });
  289. afterEach(closeAllWindows);
  290. it('resolves when done loading', async () => {
  291. await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
  292. });
  293. it('resolves when done loading a file URL', async () => {
  294. await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled();
  295. });
  296. it('rejects when failing to load a file URL', async () => {
  297. await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected()
  298. .and.have.property('code', 'ERR_FILE_NOT_FOUND');
  299. });
  300. // Temporarily disable on WOA until
  301. // https://github.com/electron/electron/issues/20008 is resolved
  302. const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it);
  303. testFn('rejects when loading fails due to DNS not resolved', async () => {
  304. await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected()
  305. .and.have.property('code', 'ERR_NAME_NOT_RESOLVED');
  306. });
  307. it('rejects when navigation is cancelled due to a bad scheme', async () => {
  308. await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected()
  309. .and.have.property('code', 'ERR_FAILED');
  310. });
  311. it('sets appropriate error information on rejection', async () => {
  312. let err: any;
  313. try {
  314. await w.loadURL('file:non-existent');
  315. } catch (e) {
  316. err = e;
  317. }
  318. expect(err).not.to.be.null();
  319. expect(err.code).to.eql('ERR_FILE_NOT_FOUND');
  320. expect(err.errno).to.eql(-6);
  321. expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent');
  322. });
  323. it('rejects if the load is aborted', async () => {
  324. const s = http.createServer(() => { /* never complete the request */ });
  325. await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve));
  326. const { port } = s.address() as AddressInfo;
  327. const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/);
  328. // load a different file before the first load completes, causing the
  329. // first load to be aborted.
  330. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  331. await p;
  332. s.close();
  333. });
  334. it("doesn't reject when a subframe fails to load", async () => {
  335. let resp = null as unknown as http.ServerResponse;
  336. const s = http.createServer((req, res) => {
  337. res.writeHead(200, { 'Content-Type': 'text/html' });
  338. res.write('<iframe src="http://err.name.not.resolved"></iframe>');
  339. resp = res;
  340. // don't end the response yet
  341. });
  342. await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve));
  343. const { port } = s.address() as AddressInfo;
  344. const p = new Promise<void>(resolve => {
  345. w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => {
  346. if (!isMainFrame) {
  347. resolve();
  348. }
  349. });
  350. });
  351. const main = w.loadURL(`http://127.0.0.1:${port}`);
  352. await p;
  353. resp.end();
  354. await main;
  355. s.close();
  356. });
  357. it("doesn't resolve when a subframe loads", async () => {
  358. let resp = null as unknown as http.ServerResponse;
  359. const s = http.createServer((req, res) => {
  360. res.writeHead(200, { 'Content-Type': 'text/html' });
  361. res.write('<iframe src="about:blank"></iframe>');
  362. resp = res;
  363. // don't end the response yet
  364. });
  365. await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve));
  366. const { port } = s.address() as AddressInfo;
  367. const p = new Promise<void>(resolve => {
  368. w.webContents.on('did-frame-finish-load', (event, isMainFrame) => {
  369. if (!isMainFrame) {
  370. resolve();
  371. }
  372. });
  373. });
  374. const main = w.loadURL(`http://127.0.0.1:${port}`);
  375. await p;
  376. resp.destroy(); // cause the main request to fail
  377. await expect(main).to.eventually.be.rejected()
  378. .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING
  379. s.close();
  380. });
  381. });
  382. describe('getFocusedWebContents() API', () => {
  383. afterEach(closeAllWindows);
  384. const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it);
  385. testFn('returns the focused web contents', async () => {
  386. const w = new BrowserWindow({ show: true });
  387. await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  388. expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id);
  389. const devToolsOpened = emittedOnce(w.webContents, 'devtools-opened');
  390. w.webContents.openDevTools();
  391. await devToolsOpened;
  392. expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.devToolsWebContents!.id);
  393. const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed');
  394. w.webContents.closeDevTools();
  395. await devToolsClosed;
  396. expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id);
  397. });
  398. it('does not crash when called on a detached dev tools window', async () => {
  399. const w = new BrowserWindow({ show: true });
  400. w.webContents.openDevTools({ mode: 'detach' });
  401. w.webContents.inspectElement(100, 100);
  402. // For some reason we have to wait for two focused events...?
  403. await emittedOnce(w.webContents, 'devtools-focused');
  404. expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
  405. // Work around https://github.com/electron/electron/issues/19985
  406. await delay();
  407. const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed');
  408. w.webContents.closeDevTools();
  409. await devToolsClosed;
  410. expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
  411. });
  412. });
  413. describe('setDevToolsWebContents() API', () => {
  414. afterEach(closeAllWindows);
  415. it('sets arbitrary webContents as devtools', async () => {
  416. const w = new BrowserWindow({ show: false });
  417. const devtools = new BrowserWindow({ show: false });
  418. const promise = emittedOnce(devtools.webContents, 'dom-ready');
  419. w.webContents.setDevToolsWebContents(devtools.webContents);
  420. w.webContents.openDevTools();
  421. await promise;
  422. expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true();
  423. const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name');
  424. expect(result).to.equal('InspectorFrontendHostImpl');
  425. devtools.destroy();
  426. });
  427. });
  428. describe('isFocused() API', () => {
  429. it('returns false when the window is hidden', async () => {
  430. const w = new BrowserWindow({ show: false });
  431. await w.loadURL('about:blank');
  432. expect(w.isVisible()).to.be.false();
  433. expect(w.webContents.isFocused()).to.be.false();
  434. });
  435. });
  436. describe('isCurrentlyAudible() API', () => {
  437. afterEach(closeAllWindows);
  438. it('returns whether audio is playing', async () => {
  439. const w = new BrowserWindow({ show: false });
  440. await w.loadURL('about:blank');
  441. await w.webContents.executeJavaScript(`
  442. window.context = new AudioContext
  443. // Start in suspended state, because of the
  444. // new web audio api policy.
  445. context.suspend()
  446. window.oscillator = context.createOscillator()
  447. oscillator.connect(context.destination)
  448. oscillator.start()
  449. `);
  450. let p = emittedOnce(w.webContents, '-audio-state-changed');
  451. w.webContents.executeJavaScript('context.resume()');
  452. await p;
  453. expect(w.webContents.isCurrentlyAudible()).to.be.true();
  454. p = emittedOnce(w.webContents, '-audio-state-changed');
  455. w.webContents.executeJavaScript('oscillator.stop()');
  456. await p;
  457. expect(w.webContents.isCurrentlyAudible()).to.be.false();
  458. });
  459. });
  460. describe('openDevTools() API', () => {
  461. afterEach(closeAllWindows);
  462. it('can show window with activation', async () => {
  463. const w = new BrowserWindow({ show: false });
  464. const focused = emittedOnce(w, 'focus');
  465. w.show();
  466. await focused;
  467. expect(w.isFocused()).to.be.true();
  468. const blurred = emittedOnce(w, 'blur');
  469. w.webContents.openDevTools({ mode: 'detach', activate: true });
  470. await Promise.all([
  471. emittedOnce(w.webContents, 'devtools-opened'),
  472. emittedOnce(w.webContents, 'devtools-focused')
  473. ]);
  474. await blurred;
  475. expect(w.isFocused()).to.be.false();
  476. });
  477. it('can show window without activation', async () => {
  478. const w = new BrowserWindow({ show: false });
  479. const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened');
  480. w.webContents.openDevTools({ mode: 'detach', activate: false });
  481. await devtoolsOpened;
  482. expect(w.webContents.isDevToolsOpened()).to.be.true();
  483. });
  484. });
  485. describe('before-input-event event', () => {
  486. afterEach(closeAllWindows);
  487. it('can prevent document keyboard events', async () => {
  488. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  489. await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
  490. const keyDown = new Promise(resolve => {
  491. ipcMain.once('keydown', (event, key) => resolve(key));
  492. });
  493. w.webContents.once('before-input-event', (event, input) => {
  494. if (input.key === 'a') event.preventDefault();
  495. });
  496. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' });
  497. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' });
  498. expect(await keyDown).to.equal('b');
  499. });
  500. it('has the correct properties', async () => {
  501. const w = new BrowserWindow({ show: false });
  502. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  503. const testBeforeInput = async (opts: any) => {
  504. const modifiers = [];
  505. if (opts.shift) modifiers.push('shift');
  506. if (opts.control) modifiers.push('control');
  507. if (opts.alt) modifiers.push('alt');
  508. if (opts.meta) modifiers.push('meta');
  509. if (opts.isAutoRepeat) modifiers.push('isAutoRepeat');
  510. const p = emittedOnce(w.webContents, 'before-input-event');
  511. w.webContents.sendInputEvent({
  512. type: opts.type,
  513. keyCode: opts.keyCode,
  514. modifiers: modifiers as any
  515. });
  516. const [, input] = await p;
  517. expect(input.type).to.equal(opts.type);
  518. expect(input.key).to.equal(opts.key);
  519. expect(input.code).to.equal(opts.code);
  520. expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat);
  521. expect(input.shift).to.equal(opts.shift);
  522. expect(input.control).to.equal(opts.control);
  523. expect(input.alt).to.equal(opts.alt);
  524. expect(input.meta).to.equal(opts.meta);
  525. };
  526. await testBeforeInput({
  527. type: 'keyDown',
  528. key: 'A',
  529. code: 'KeyA',
  530. keyCode: 'a',
  531. shift: true,
  532. control: true,
  533. alt: true,
  534. meta: true,
  535. isAutoRepeat: true
  536. });
  537. await testBeforeInput({
  538. type: 'keyUp',
  539. key: '.',
  540. code: 'Period',
  541. keyCode: '.',
  542. shift: false,
  543. control: true,
  544. alt: true,
  545. meta: false,
  546. isAutoRepeat: false
  547. });
  548. await testBeforeInput({
  549. type: 'keyUp',
  550. key: '!',
  551. code: 'Digit1',
  552. keyCode: '1',
  553. shift: true,
  554. control: false,
  555. alt: false,
  556. meta: true,
  557. isAutoRepeat: false
  558. });
  559. await testBeforeInput({
  560. type: 'keyUp',
  561. key: 'Tab',
  562. code: 'Tab',
  563. keyCode: 'Tab',
  564. shift: false,
  565. control: true,
  566. alt: false,
  567. meta: false,
  568. isAutoRepeat: true
  569. });
  570. });
  571. });
  572. // On Mac, zooming isn't done with the mouse wheel.
  573. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => {
  574. afterEach(closeAllWindows);
  575. it('is emitted with the correct zoom-in info', async () => {
  576. const w = new BrowserWindow({ show: false });
  577. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  578. const testZoomChanged = async () => {
  579. w.webContents.sendInputEvent({
  580. type: 'mouseWheel',
  581. x: 300,
  582. y: 300,
  583. deltaX: 0,
  584. deltaY: 1,
  585. wheelTicksX: 0,
  586. wheelTicksY: 1,
  587. modifiers: ['control', 'meta']
  588. });
  589. const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed');
  590. expect(zoomDirection).to.equal('in');
  591. };
  592. await testZoomChanged();
  593. });
  594. it('is emitted with the correct zoom-out info', async () => {
  595. const w = new BrowserWindow({ show: false });
  596. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  597. const testZoomChanged = async () => {
  598. w.webContents.sendInputEvent({
  599. type: 'mouseWheel',
  600. x: 300,
  601. y: 300,
  602. deltaX: 0,
  603. deltaY: -1,
  604. wheelTicksX: 0,
  605. wheelTicksY: -1,
  606. modifiers: ['control', 'meta']
  607. });
  608. const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed');
  609. expect(zoomDirection).to.equal('out');
  610. };
  611. await testZoomChanged();
  612. });
  613. });
  614. describe('sendInputEvent(event)', () => {
  615. let w: BrowserWindow;
  616. beforeEach(async () => {
  617. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  618. await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
  619. });
  620. afterEach(closeAllWindows);
  621. it('can send keydown events', async () => {
  622. const keydown = emittedOnce(ipcMain, 'keydown');
  623. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
  624. const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
  625. expect(key).to.equal('a');
  626. expect(code).to.equal('KeyA');
  627. expect(keyCode).to.equal(65);
  628. expect(shiftKey).to.be.false();
  629. expect(ctrlKey).to.be.false();
  630. expect(altKey).to.be.false();
  631. });
  632. it('can send keydown events with modifiers', async () => {
  633. const keydown = emittedOnce(ipcMain, 'keydown');
  634. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
  635. const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
  636. expect(key).to.equal('Z');
  637. expect(code).to.equal('KeyZ');
  638. expect(keyCode).to.equal(90);
  639. expect(shiftKey).to.be.true();
  640. expect(ctrlKey).to.be.true();
  641. expect(altKey).to.be.false();
  642. });
  643. it('can send keydown events with special keys', async () => {
  644. const keydown = emittedOnce(ipcMain, 'keydown');
  645. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] });
  646. const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
  647. expect(key).to.equal('Tab');
  648. expect(code).to.equal('Tab');
  649. expect(keyCode).to.equal(9);
  650. expect(shiftKey).to.be.false();
  651. expect(ctrlKey).to.be.false();
  652. expect(altKey).to.be.true();
  653. });
  654. it('can send char events', async () => {
  655. const keypress = emittedOnce(ipcMain, 'keypress');
  656. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
  657. w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' });
  658. const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
  659. expect(key).to.equal('a');
  660. expect(code).to.equal('KeyA');
  661. expect(keyCode).to.equal(65);
  662. expect(shiftKey).to.be.false();
  663. expect(ctrlKey).to.be.false();
  664. expect(altKey).to.be.false();
  665. });
  666. it('can send char events with modifiers', async () => {
  667. const keypress = emittedOnce(ipcMain, 'keypress');
  668. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' });
  669. w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
  670. const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
  671. expect(key).to.equal('Z');
  672. expect(code).to.equal('KeyZ');
  673. expect(keyCode).to.equal(90);
  674. expect(shiftKey).to.be.true();
  675. expect(ctrlKey).to.be.true();
  676. expect(altKey).to.be.false();
  677. });
  678. });
  679. describe('insertCSS', () => {
  680. afterEach(closeAllWindows);
  681. it('supports inserting CSS', async () => {
  682. const w = new BrowserWindow({ show: false });
  683. w.loadURL('about:blank');
  684. await w.webContents.insertCSS('body { background-repeat: round; }');
  685. const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
  686. expect(result).to.equal('round');
  687. });
  688. it('supports removing inserted CSS', async () => {
  689. const w = new BrowserWindow({ show: false });
  690. w.loadURL('about:blank');
  691. const key = await w.webContents.insertCSS('body { background-repeat: round; }');
  692. await w.webContents.removeInsertedCSS(key);
  693. const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
  694. expect(result).to.equal('repeat');
  695. });
  696. });
  697. describe('inspectElement()', () => {
  698. afterEach(closeAllWindows);
  699. it('supports inspecting an element in the devtools', (done) => {
  700. const w = new BrowserWindow({ show: false });
  701. w.loadURL('about:blank');
  702. w.webContents.once('devtools-opened', () => { done(); });
  703. w.webContents.inspectElement(10, 10);
  704. });
  705. });
  706. describe('startDrag({file, icon})', () => {
  707. it('throws errors for a missing file or a missing/empty icon', () => {
  708. const w = new BrowserWindow({ show: false });
  709. expect(() => {
  710. w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any);
  711. }).to.throw('Must specify either \'file\' or \'files\' option');
  712. expect(() => {
  713. w.webContents.startDrag({ file: __filename } as any);
  714. }).to.throw('\'icon\' parameter is required');
  715. expect(() => {
  716. w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') });
  717. }).to.throw(/Failed to load image from path (.+)/);
  718. });
  719. });
  720. describe('focus APIs', () => {
  721. describe('focus()', () => {
  722. afterEach(closeAllWindows);
  723. it('does not blur the focused window when the web contents is hidden', async () => {
  724. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  725. w.show();
  726. await w.loadURL('about:blank');
  727. w.focus();
  728. const child = new BrowserWindow({ show: false });
  729. child.loadURL('about:blank');
  730. child.webContents.focus();
  731. const currentFocused = w.isFocused();
  732. const childFocused = child.isFocused();
  733. child.close();
  734. expect(currentFocused).to.be.true();
  735. expect(childFocused).to.be.false();
  736. });
  737. });
  738. const moveFocusToDevTools = async (win: BrowserWindow) => {
  739. const devToolsOpened = emittedOnce(win.webContents, 'devtools-opened');
  740. win.webContents.openDevTools({ mode: 'right' });
  741. await devToolsOpened;
  742. win.webContents.devToolsWebContents!.focus();
  743. };
  744. describe('focus event', () => {
  745. afterEach(closeAllWindows);
  746. it('is triggered when web contents is focused', async () => {
  747. const w = new BrowserWindow({ show: false });
  748. await w.loadURL('about:blank');
  749. await moveFocusToDevTools(w);
  750. const focusPromise = emittedOnce(w.webContents, 'focus');
  751. w.webContents.focus();
  752. await expect(focusPromise).to.eventually.be.fulfilled();
  753. });
  754. it('is triggered when BrowserWindow is focused', async () => {
  755. const window1 = new BrowserWindow({ show: false });
  756. const window2 = new BrowserWindow({ show: false });
  757. await Promise.all([
  758. window1.loadURL('about:blank'),
  759. window2.loadURL('about:blank')
  760. ]);
  761. const focusPromise1 = emittedOnce(window1.webContents, 'focus');
  762. const focusPromise2 = emittedOnce(window2.webContents, 'focus');
  763. window1.showInactive();
  764. window2.showInactive();
  765. window1.focus();
  766. await expect(focusPromise1).to.eventually.be.fulfilled();
  767. window2.focus();
  768. await expect(focusPromise2).to.eventually.be.fulfilled();
  769. });
  770. });
  771. describe('blur event', () => {
  772. afterEach(closeAllWindows);
  773. it('is triggered when web contents is blurred', async () => {
  774. const w = new BrowserWindow({ show: true });
  775. await w.loadURL('about:blank');
  776. w.webContents.focus();
  777. const blurPromise = emittedOnce(w.webContents, 'blur');
  778. await moveFocusToDevTools(w);
  779. await expect(blurPromise).to.eventually.be.fulfilled();
  780. });
  781. });
  782. });
  783. describe('getOSProcessId()', () => {
  784. afterEach(closeAllWindows);
  785. it('returns a valid process id', async () => {
  786. const w = new BrowserWindow({ show: false });
  787. expect(w.webContents.getOSProcessId()).to.equal(0);
  788. await w.loadURL('about:blank');
  789. expect(w.webContents.getOSProcessId()).to.be.above(0);
  790. });
  791. });
  792. describe('getMediaSourceId()', () => {
  793. afterEach(closeAllWindows);
  794. it('returns a valid stream id', () => {
  795. const w = new BrowserWindow({ show: false });
  796. expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty();
  797. });
  798. });
  799. describe('userAgent APIs', () => {
  800. it('is not empty by default', () => {
  801. const w = new BrowserWindow({ show: false });
  802. const userAgent = w.webContents.getUserAgent();
  803. expect(userAgent).to.be.a('string').that.is.not.empty();
  804. });
  805. it('can set the user agent (functions)', () => {
  806. const w = new BrowserWindow({ show: false });
  807. const userAgent = w.webContents.getUserAgent();
  808. w.webContents.setUserAgent('my-user-agent');
  809. expect(w.webContents.getUserAgent()).to.equal('my-user-agent');
  810. w.webContents.setUserAgent(userAgent);
  811. expect(w.webContents.getUserAgent()).to.equal(userAgent);
  812. });
  813. it('can set the user agent (properties)', () => {
  814. const w = new BrowserWindow({ show: false });
  815. const userAgent = w.webContents.userAgent;
  816. w.webContents.userAgent = 'my-user-agent';
  817. expect(w.webContents.userAgent).to.equal('my-user-agent');
  818. w.webContents.userAgent = userAgent;
  819. expect(w.webContents.userAgent).to.equal(userAgent);
  820. });
  821. });
  822. describe('audioMuted APIs', () => {
  823. it('can set the audio mute level (functions)', () => {
  824. const w = new BrowserWindow({ show: false });
  825. w.webContents.setAudioMuted(true);
  826. expect(w.webContents.isAudioMuted()).to.be.true();
  827. w.webContents.setAudioMuted(false);
  828. expect(w.webContents.isAudioMuted()).to.be.false();
  829. });
  830. it('can set the audio mute level (functions)', () => {
  831. const w = new BrowserWindow({ show: false });
  832. w.webContents.audioMuted = true;
  833. expect(w.webContents.audioMuted).to.be.true();
  834. w.webContents.audioMuted = false;
  835. expect(w.webContents.audioMuted).to.be.false();
  836. });
  837. });
  838. describe('zoom api', () => {
  839. const hostZoomMap: Record<string, number> = {
  840. host1: 0.3,
  841. host2: 0.7,
  842. host3: 0.2
  843. };
  844. before(() => {
  845. const protocol = session.defaultSession.protocol;
  846. protocol.registerStringProtocol(standardScheme, (request, callback) => {
  847. const response = `<script>
  848. const {ipcRenderer} = require('electron')
  849. ipcRenderer.send('set-zoom', window.location.hostname)
  850. ipcRenderer.on(window.location.hostname + '-zoom-set', () => {
  851. ipcRenderer.send(window.location.hostname + '-zoom-level')
  852. })
  853. </script>`;
  854. callback({ data: response, mimeType: 'text/html' });
  855. });
  856. });
  857. after(() => {
  858. const protocol = session.defaultSession.protocol;
  859. protocol.unregisterProtocol(standardScheme);
  860. });
  861. afterEach(closeAllWindows);
  862. it('throws on an invalid zoomFactor', async () => {
  863. const w = new BrowserWindow({ show: false });
  864. await w.loadURL('about:blank');
  865. expect(() => {
  866. w.webContents.setZoomFactor(0.0);
  867. }).to.throw(/'zoomFactor' must be a double greater than 0.0/);
  868. expect(() => {
  869. w.webContents.setZoomFactor(-2.0);
  870. }).to.throw(/'zoomFactor' must be a double greater than 0.0/);
  871. });
  872. it('can set the correct zoom level (functions)', async () => {
  873. const w = new BrowserWindow({ show: false });
  874. try {
  875. await w.loadURL('about:blank');
  876. const zoomLevel = w.webContents.getZoomLevel();
  877. expect(zoomLevel).to.eql(0.0);
  878. w.webContents.setZoomLevel(0.5);
  879. const newZoomLevel = w.webContents.getZoomLevel();
  880. expect(newZoomLevel).to.eql(0.5);
  881. } finally {
  882. w.webContents.setZoomLevel(0);
  883. }
  884. });
  885. it('can set the correct zoom level (properties)', async () => {
  886. const w = new BrowserWindow({ show: false });
  887. try {
  888. await w.loadURL('about:blank');
  889. const zoomLevel = w.webContents.zoomLevel;
  890. expect(zoomLevel).to.eql(0.0);
  891. w.webContents.zoomLevel = 0.5;
  892. const newZoomLevel = w.webContents.zoomLevel;
  893. expect(newZoomLevel).to.eql(0.5);
  894. } finally {
  895. w.webContents.zoomLevel = 0;
  896. }
  897. });
  898. it('can set the correct zoom factor (functions)', async () => {
  899. const w = new BrowserWindow({ show: false });
  900. try {
  901. await w.loadURL('about:blank');
  902. const zoomFactor = w.webContents.getZoomFactor();
  903. expect(zoomFactor).to.eql(1.0);
  904. w.webContents.setZoomFactor(0.5);
  905. const newZoomFactor = w.webContents.getZoomFactor();
  906. expect(newZoomFactor).to.eql(0.5);
  907. } finally {
  908. w.webContents.setZoomFactor(1.0);
  909. }
  910. });
  911. it('can set the correct zoom factor (properties)', async () => {
  912. const w = new BrowserWindow({ show: false });
  913. try {
  914. await w.loadURL('about:blank');
  915. const zoomFactor = w.webContents.zoomFactor;
  916. expect(zoomFactor).to.eql(1.0);
  917. w.webContents.zoomFactor = 0.5;
  918. const newZoomFactor = w.webContents.zoomFactor;
  919. expect(newZoomFactor).to.eql(0.5);
  920. } finally {
  921. w.webContents.zoomFactor = 1.0;
  922. }
  923. });
  924. it('can persist zoom level across navigation', (done) => {
  925. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  926. let finalNavigation = false;
  927. ipcMain.on('set-zoom', (e, host) => {
  928. const zoomLevel = hostZoomMap[host];
  929. if (!finalNavigation) w.webContents.zoomLevel = zoomLevel;
  930. e.sender.send(`${host}-zoom-set`);
  931. });
  932. ipcMain.on('host1-zoom-level', (e) => {
  933. try {
  934. const zoomLevel = e.sender.getZoomLevel();
  935. const expectedZoomLevel = hostZoomMap.host1;
  936. expect(zoomLevel).to.equal(expectedZoomLevel);
  937. if (finalNavigation) {
  938. done();
  939. } else {
  940. w.loadURL(`${standardScheme}://host2`);
  941. }
  942. } catch (e) {
  943. done(e);
  944. }
  945. });
  946. ipcMain.once('host2-zoom-level', (e) => {
  947. try {
  948. const zoomLevel = e.sender.getZoomLevel();
  949. const expectedZoomLevel = hostZoomMap.host2;
  950. expect(zoomLevel).to.equal(expectedZoomLevel);
  951. finalNavigation = true;
  952. w.webContents.goBack();
  953. } catch (e) {
  954. done(e);
  955. }
  956. });
  957. w.loadURL(`${standardScheme}://host1`);
  958. });
  959. it('can propagate zoom level across same session', async () => {
  960. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  961. const w2 = new BrowserWindow({ show: false });
  962. defer(() => {
  963. w2.setClosable(true);
  964. w2.close();
  965. });
  966. await w.loadURL(`${standardScheme}://host3`);
  967. w.webContents.zoomLevel = hostZoomMap.host3;
  968. await w2.loadURL(`${standardScheme}://host3`);
  969. const zoomLevel1 = w.webContents.zoomLevel;
  970. expect(zoomLevel1).to.equal(hostZoomMap.host3);
  971. const zoomLevel2 = w2.webContents.zoomLevel;
  972. expect(zoomLevel1).to.equal(zoomLevel2);
  973. });
  974. it('cannot propagate zoom level across different session', async () => {
  975. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  976. const w2 = new BrowserWindow({
  977. show: false,
  978. webPreferences: {
  979. partition: 'temp'
  980. }
  981. });
  982. const protocol = w2.webContents.session.protocol;
  983. protocol.registerStringProtocol(standardScheme, (request, callback) => {
  984. callback('hello');
  985. });
  986. defer(() => {
  987. w2.setClosable(true);
  988. w2.close();
  989. protocol.unregisterProtocol(standardScheme);
  990. });
  991. await w.loadURL(`${standardScheme}://host3`);
  992. w.webContents.zoomLevel = hostZoomMap.host3;
  993. await w2.loadURL(`${standardScheme}://host3`);
  994. const zoomLevel1 = w.webContents.zoomLevel;
  995. expect(zoomLevel1).to.equal(hostZoomMap.host3);
  996. const zoomLevel2 = w2.webContents.zoomLevel;
  997. expect(zoomLevel2).to.equal(0);
  998. expect(zoomLevel1).to.not.equal(zoomLevel2);
  999. });
  1000. it('can persist when it contains iframe', (done) => {
  1001. const w = new BrowserWindow({ show: false });
  1002. const server = http.createServer((req, res) => {
  1003. setTimeout(() => {
  1004. res.end();
  1005. }, 200);
  1006. });
  1007. server.listen(0, '127.0.0.1', () => {
  1008. const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  1009. const content = `<iframe src=${url}></iframe>`;
  1010. w.webContents.on('did-frame-finish-load', (e, isMainFrame) => {
  1011. if (!isMainFrame) {
  1012. try {
  1013. const zoomLevel = w.webContents.zoomLevel;
  1014. expect(zoomLevel).to.equal(2.0);
  1015. w.webContents.zoomLevel = 0;
  1016. done();
  1017. } catch (e) {
  1018. done(e);
  1019. } finally {
  1020. server.close();
  1021. }
  1022. }
  1023. });
  1024. w.webContents.on('dom-ready', () => {
  1025. w.webContents.zoomLevel = 2.0;
  1026. });
  1027. w.loadURL(`data:text/html,${content}`);
  1028. });
  1029. });
  1030. it('cannot propagate when used with webframe', async () => {
  1031. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1032. const w2 = new BrowserWindow({ show: false });
  1033. const temporaryZoomSet = emittedOnce(ipcMain, 'temporary-zoom-set');
  1034. w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html'));
  1035. await temporaryZoomSet;
  1036. const finalZoomLevel = w.webContents.getZoomLevel();
  1037. await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html'));
  1038. const zoomLevel1 = w.webContents.zoomLevel;
  1039. const zoomLevel2 = w2.webContents.zoomLevel;
  1040. w2.setClosable(true);
  1041. w2.close();
  1042. expect(zoomLevel1).to.equal(finalZoomLevel);
  1043. expect(zoomLevel2).to.equal(0);
  1044. expect(zoomLevel1).to.not.equal(zoomLevel2);
  1045. });
  1046. describe('with unique domains', () => {
  1047. let server: http.Server;
  1048. let serverUrl: string;
  1049. let crossSiteUrl: string;
  1050. before((done) => {
  1051. server = http.createServer((req, res) => {
  1052. setTimeout(() => res.end('hey'), 0);
  1053. });
  1054. server.listen(0, '127.0.0.1', () => {
  1055. serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  1056. crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`;
  1057. done();
  1058. });
  1059. });
  1060. after(() => {
  1061. server.close();
  1062. });
  1063. it('cannot persist zoom level after navigation with webFrame', async () => {
  1064. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1065. const source = `
  1066. const {ipcRenderer, webFrame} = require('electron')
  1067. webFrame.setZoomLevel(0.6)
  1068. ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel())
  1069. `;
  1070. const zoomLevelPromise = emittedOnce(ipcMain, 'zoom-level-set');
  1071. await w.loadURL(serverUrl);
  1072. await w.webContents.executeJavaScript(source);
  1073. let [, zoomLevel] = await zoomLevelPromise;
  1074. expect(zoomLevel).to.equal(0.6);
  1075. const loadPromise = emittedOnce(w.webContents, 'did-finish-load');
  1076. await w.loadURL(crossSiteUrl);
  1077. await loadPromise;
  1078. zoomLevel = w.webContents.zoomLevel;
  1079. expect(zoomLevel).to.equal(0);
  1080. });
  1081. });
  1082. });
  1083. describe('webrtc ip policy api', () => {
  1084. afterEach(closeAllWindows);
  1085. it('can set and get webrtc ip policies', () => {
  1086. const w = new BrowserWindow({ show: false });
  1087. const policies = [
  1088. 'default',
  1089. 'default_public_interface_only',
  1090. 'default_public_and_private_interfaces',
  1091. 'disable_non_proxied_udp'
  1092. ];
  1093. policies.forEach((policy) => {
  1094. w.webContents.setWebRTCIPHandlingPolicy(policy as any);
  1095. expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy);
  1096. });
  1097. });
  1098. });
  1099. describe('render view deleted events', () => {
  1100. let server: http.Server;
  1101. let serverUrl: string;
  1102. let crossSiteUrl: string;
  1103. before((done) => {
  1104. server = http.createServer((req, res) => {
  1105. const respond = () => {
  1106. if (req.url === '/redirect-cross-site') {
  1107. res.setHeader('Location', `${crossSiteUrl}/redirected`);
  1108. res.statusCode = 302;
  1109. res.end();
  1110. } else if (req.url === '/redirected') {
  1111. res.end('<html><script>window.localStorage</script></html>');
  1112. } else if (req.url === '/first-window-open') {
  1113. res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`);
  1114. } else if (req.url === '/second-window-open') {
  1115. res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>');
  1116. } else {
  1117. res.end();
  1118. }
  1119. };
  1120. setTimeout(respond, 0);
  1121. });
  1122. server.listen(0, '127.0.0.1', () => {
  1123. serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  1124. crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`;
  1125. done();
  1126. });
  1127. });
  1128. after(() => {
  1129. server.close();
  1130. });
  1131. afterEach(closeAllWindows);
  1132. it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
  1133. const w = new BrowserWindow({ show: false });
  1134. let currentRenderViewDeletedEmitted = false;
  1135. const renderViewDeletedHandler = () => {
  1136. currentRenderViewDeletedEmitted = true;
  1137. };
  1138. w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
  1139. w.webContents.on('did-finish-load', () => {
  1140. w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
  1141. w.close();
  1142. });
  1143. const destroyed = emittedOnce(w.webContents, 'destroyed');
  1144. w.loadURL(`${serverUrl}/redirect-cross-site`);
  1145. await destroyed;
  1146. expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted');
  1147. });
  1148. it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
  1149. const parentWindow = new BrowserWindow({ show: false });
  1150. let currentRenderViewDeletedEmitted = false;
  1151. let childWindow: BrowserWindow | null = null;
  1152. const destroyed = emittedOnce(parentWindow.webContents, 'destroyed');
  1153. const renderViewDeletedHandler = () => {
  1154. currentRenderViewDeletedEmitted = true;
  1155. };
  1156. const childWindowCreated = new Promise<void>((resolve) => {
  1157. app.once('browser-window-created', (event, window) => {
  1158. childWindow = window;
  1159. window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
  1160. resolve();
  1161. });
  1162. });
  1163. parentWindow.loadURL(`${serverUrl}/first-window-open`);
  1164. await childWindowCreated;
  1165. childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
  1166. parentWindow.close();
  1167. await destroyed;
  1168. expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed');
  1169. });
  1170. it('emits current-render-view-deleted if the current RVHs are deleted', async () => {
  1171. const w = new BrowserWindow({ show: false });
  1172. let currentRenderViewDeletedEmitted = false;
  1173. w.webContents.on('current-render-view-deleted' as any, () => {
  1174. currentRenderViewDeletedEmitted = true;
  1175. });
  1176. w.webContents.on('did-finish-load', () => {
  1177. w.close();
  1178. });
  1179. const destroyed = emittedOnce(w.webContents, 'destroyed');
  1180. w.loadURL(`${serverUrl}/redirect-cross-site`);
  1181. await destroyed;
  1182. expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted');
  1183. });
  1184. it('emits render-view-deleted if any RVHs are deleted', async () => {
  1185. const w = new BrowserWindow({ show: false });
  1186. let rvhDeletedCount = 0;
  1187. w.webContents.on('render-view-deleted' as any, () => {
  1188. rvhDeletedCount++;
  1189. });
  1190. w.webContents.on('did-finish-load', () => {
  1191. w.close();
  1192. });
  1193. const destroyed = emittedOnce(w.webContents, 'destroyed');
  1194. w.loadURL(`${serverUrl}/redirect-cross-site`);
  1195. await destroyed;
  1196. const expectedRenderViewDeletedEventCount = 1;
  1197. expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times');
  1198. });
  1199. });
  1200. describe('setIgnoreMenuShortcuts(ignore)', () => {
  1201. afterEach(closeAllWindows);
  1202. it('does not throw', () => {
  1203. const w = new BrowserWindow({ show: false });
  1204. expect(() => {
  1205. w.webContents.setIgnoreMenuShortcuts(true);
  1206. w.webContents.setIgnoreMenuShortcuts(false);
  1207. }).to.not.throw();
  1208. });
  1209. });
  1210. const crashPrefs = [
  1211. {
  1212. nodeIntegration: true
  1213. },
  1214. {
  1215. sandbox: true
  1216. }
  1217. ];
  1218. const nicePrefs = (o: any) => {
  1219. let s = '';
  1220. for (const key of Object.keys(o)) {
  1221. s += `${key}=${o[key]}, `;
  1222. }
  1223. return `(${s.slice(0, s.length - 2)})`;
  1224. };
  1225. for (const prefs of crashPrefs) {
  1226. describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => {
  1227. let w: BrowserWindow;
  1228. beforeEach(async () => {
  1229. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  1230. await w.loadURL('about:blank');
  1231. });
  1232. afterEach(closeAllWindows);
  1233. it('isCrashed() is false by default', () => {
  1234. expect(w.webContents.isCrashed()).to.equal(false);
  1235. });
  1236. it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => {
  1237. expect(w.webContents.isCrashed()).to.equal(false);
  1238. const crashEvent = emittedOnce(w.webContents, 'render-process-gone');
  1239. w.webContents.forcefullyCrashRenderer();
  1240. const [, details] = await crashEvent;
  1241. expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed');
  1242. expect(w.webContents.isCrashed()).to.equal(true);
  1243. });
  1244. it('a crashed process is recoverable with reload()', async () => {
  1245. expect(w.webContents.isCrashed()).to.equal(false);
  1246. w.webContents.forcefullyCrashRenderer();
  1247. w.webContents.reload();
  1248. expect(w.webContents.isCrashed()).to.equal(false);
  1249. });
  1250. });
  1251. }
  1252. // Destroying webContents in its event listener is going to crash when
  1253. // Electron is built in Debug mode.
  1254. describe('destroy()', () => {
  1255. let server: http.Server;
  1256. let serverUrl: string;
  1257. before((done) => {
  1258. server = http.createServer((request, response) => {
  1259. switch (request.url) {
  1260. case '/net-error':
  1261. response.destroy();
  1262. break;
  1263. case '/200':
  1264. response.end();
  1265. break;
  1266. default:
  1267. done('unsupported endpoint');
  1268. }
  1269. }).listen(0, '127.0.0.1', () => {
  1270. serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  1271. done();
  1272. });
  1273. });
  1274. after(() => {
  1275. server.close();
  1276. });
  1277. const events = [
  1278. { name: 'did-start-loading', url: '/200' },
  1279. { name: 'dom-ready', url: '/200' },
  1280. { name: 'did-stop-loading', url: '/200' },
  1281. { name: 'did-finish-load', url: '/200' },
  1282. // FIXME: Multiple Emit calls inside an observer assume that object
  1283. // will be alive till end of the observer. Synchronous `destroy` api
  1284. // violates this contract and crashes.
  1285. { name: 'did-frame-finish-load', url: '/200' },
  1286. { name: 'did-fail-load', url: '/net-error' }
  1287. ];
  1288. for (const e of events) {
  1289. it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () {
  1290. // This test is flaky on Windows CI and we don't know why, but the
  1291. // purpose of this test is to make sure Electron does not crash so it
  1292. // is fine to retry this test for a few times.
  1293. this.retries(3);
  1294. const contents = (webContents as any).create() as WebContents;
  1295. const originalEmit = contents.emit.bind(contents);
  1296. contents.emit = (...args) => { return originalEmit(...args); };
  1297. contents.once(e.name as any, () => (contents as any).destroy());
  1298. const destroyed = emittedOnce(contents, 'destroyed');
  1299. contents.loadURL(serverUrl + e.url);
  1300. await destroyed;
  1301. });
  1302. }
  1303. });
  1304. describe('did-change-theme-color event', () => {
  1305. afterEach(closeAllWindows);
  1306. it('is triggered with correct theme color', (done) => {
  1307. const w = new BrowserWindow({ show: true });
  1308. let count = 0;
  1309. w.webContents.on('did-change-theme-color', (e, color) => {
  1310. try {
  1311. if (count === 0) {
  1312. count += 1;
  1313. expect(color).to.equal('#FFEEDD');
  1314. w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  1315. } else if (count === 1) {
  1316. expect(color).to.be.null();
  1317. done();
  1318. }
  1319. } catch (e) {
  1320. done(e);
  1321. }
  1322. });
  1323. w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html'));
  1324. });
  1325. });
  1326. describe('console-message event', () => {
  1327. afterEach(closeAllWindows);
  1328. it('is triggered with correct log message', (done) => {
  1329. const w = new BrowserWindow({ show: true });
  1330. w.webContents.on('console-message', (e, level, message) => {
  1331. // Don't just assert as Chromium might emit other logs that we should ignore.
  1332. if (message === 'a') {
  1333. done();
  1334. }
  1335. });
  1336. w.loadFile(path.join(fixturesPath, 'pages', 'a.html'));
  1337. });
  1338. });
  1339. describe('ipc-message event', () => {
  1340. afterEach(closeAllWindows);
  1341. it('emits when the renderer process sends an asynchronous message', async () => {
  1342. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1343. await w.webContents.loadURL('about:blank');
  1344. w.webContents.executeJavaScript(`
  1345. require('electron').ipcRenderer.send('message', 'Hello World!')
  1346. `);
  1347. const [, channel, message] = await emittedOnce(w.webContents, 'ipc-message');
  1348. expect(channel).to.equal('message');
  1349. expect(message).to.equal('Hello World!');
  1350. });
  1351. });
  1352. describe('ipc-message-sync event', () => {
  1353. afterEach(closeAllWindows);
  1354. it('emits when the renderer process sends a synchronous message', async () => {
  1355. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1356. await w.webContents.loadURL('about:blank');
  1357. const promise: Promise<[string, string]> = new Promise(resolve => {
  1358. w.webContents.once('ipc-message-sync', (event, channel, arg) => {
  1359. event.returnValue = 'foobar' as any;
  1360. resolve([channel, arg]);
  1361. });
  1362. });
  1363. const result = await w.webContents.executeJavaScript(`
  1364. require('electron').ipcRenderer.sendSync('message', 'Hello World!')
  1365. `);
  1366. const [channel, message] = await promise;
  1367. expect(channel).to.equal('message');
  1368. expect(message).to.equal('Hello World!');
  1369. expect(result).to.equal('foobar');
  1370. });
  1371. });
  1372. describe('referrer', () => {
  1373. afterEach(closeAllWindows);
  1374. it('propagates referrer information to new target=_blank windows', (done) => {
  1375. const w = new BrowserWindow({ show: false });
  1376. const server = http.createServer((req, res) => {
  1377. if (req.url === '/should_have_referrer') {
  1378. try {
  1379. expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
  1380. return done();
  1381. } catch (e) {
  1382. return done(e);
  1383. } finally {
  1384. server.close();
  1385. }
  1386. }
  1387. res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>');
  1388. });
  1389. server.listen(0, '127.0.0.1', () => {
  1390. const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/';
  1391. w.webContents.once('did-finish-load', () => {
  1392. w.webContents.setWindowOpenHandler(details => {
  1393. expect(details.referrer.url).to.equal(url);
  1394. expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
  1395. return { action: 'allow' };
  1396. });
  1397. w.webContents.executeJavaScript('a.click()');
  1398. });
  1399. w.loadURL(url);
  1400. });
  1401. });
  1402. // TODO(jeremy): window.open() in a real browser passes the referrer, but
  1403. // our hacked-up window.open() shim doesn't. It should.
  1404. xit('propagates referrer information to windows opened with window.open', (done) => {
  1405. const w = new BrowserWindow({ show: false });
  1406. const server = http.createServer((req, res) => {
  1407. if (req.url === '/should_have_referrer') {
  1408. try {
  1409. expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
  1410. return done();
  1411. } catch (e) {
  1412. return done(e);
  1413. }
  1414. }
  1415. res.end('');
  1416. });
  1417. server.listen(0, '127.0.0.1', () => {
  1418. const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/';
  1419. w.webContents.once('did-finish-load', () => {
  1420. w.webContents.setWindowOpenHandler(details => {
  1421. expect(details.referrer.url).to.equal(url);
  1422. expect(details.referrer.policy).to.equal('no-referrer-when-downgrade');
  1423. return { action: 'allow' };
  1424. });
  1425. w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")');
  1426. });
  1427. w.loadURL(url);
  1428. });
  1429. });
  1430. });
  1431. describe('webframe messages in sandboxed contents', () => {
  1432. afterEach(closeAllWindows);
  1433. it('responds to executeJavaScript', async () => {
  1434. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1435. await w.loadURL('about:blank');
  1436. const result = await w.webContents.executeJavaScript('37 + 5');
  1437. expect(result).to.equal(42);
  1438. });
  1439. });
  1440. describe('preload-error event', () => {
  1441. afterEach(closeAllWindows);
  1442. const generateSpecs = (description: string, sandbox: boolean) => {
  1443. describe(description, () => {
  1444. it('is triggered when unhandled exception is thrown', async () => {
  1445. const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js');
  1446. const w = new BrowserWindow({
  1447. show: false,
  1448. webPreferences: {
  1449. sandbox,
  1450. preload
  1451. }
  1452. });
  1453. const promise = emittedOnce(w.webContents, 'preload-error');
  1454. w.loadURL('about:blank');
  1455. const [, preloadPath, error] = await promise;
  1456. expect(preloadPath).to.equal(preload);
  1457. expect(error.message).to.equal('Hello World!');
  1458. });
  1459. it('is triggered on syntax errors', async () => {
  1460. const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js');
  1461. const w = new BrowserWindow({
  1462. show: false,
  1463. webPreferences: {
  1464. sandbox,
  1465. preload
  1466. }
  1467. });
  1468. const promise = emittedOnce(w.webContents, 'preload-error');
  1469. w.loadURL('about:blank');
  1470. const [, preloadPath, error] = await promise;
  1471. expect(preloadPath).to.equal(preload);
  1472. expect(error.message).to.equal('foobar is not defined');
  1473. });
  1474. it('is triggered when preload script loading fails', async () => {
  1475. const preload = path.join(fixturesPath, 'module', 'preload-invalid.js');
  1476. const w = new BrowserWindow({
  1477. show: false,
  1478. webPreferences: {
  1479. sandbox,
  1480. preload
  1481. }
  1482. });
  1483. const promise = emittedOnce(w.webContents, 'preload-error');
  1484. w.loadURL('about:blank');
  1485. const [, preloadPath, error] = await promise;
  1486. expect(preloadPath).to.equal(preload);
  1487. expect(error.message).to.contain('preload-invalid.js');
  1488. });
  1489. });
  1490. };
  1491. generateSpecs('without sandbox', false);
  1492. generateSpecs('with sandbox', true);
  1493. });
  1494. describe('takeHeapSnapshot()', () => {
  1495. afterEach(closeAllWindows);
  1496. it('works with sandboxed renderers', async () => {
  1497. const w = new BrowserWindow({
  1498. show: false,
  1499. webPreferences: {
  1500. sandbox: true
  1501. }
  1502. });
  1503. await w.loadURL('about:blank');
  1504. const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
  1505. const cleanup = () => {
  1506. try {
  1507. fs.unlinkSync(filePath);
  1508. } catch (e) {
  1509. // ignore error
  1510. }
  1511. };
  1512. try {
  1513. await w.webContents.takeHeapSnapshot(filePath);
  1514. const stats = fs.statSync(filePath);
  1515. expect(stats.size).not.to.be.equal(0);
  1516. } finally {
  1517. cleanup();
  1518. }
  1519. });
  1520. it('fails with invalid file path', async () => {
  1521. const w = new BrowserWindow({
  1522. show: false,
  1523. webPreferences: {
  1524. sandbox: true
  1525. }
  1526. });
  1527. await w.loadURL('about:blank');
  1528. const promise = w.webContents.takeHeapSnapshot('');
  1529. return expect(promise).to.be.eventually.rejectedWith(Error, 'takeHeapSnapshot failed');
  1530. });
  1531. });
  1532. describe('setBackgroundThrottling()', () => {
  1533. afterEach(closeAllWindows);
  1534. it('does not crash when allowing', () => {
  1535. const w = new BrowserWindow({ show: false });
  1536. w.webContents.setBackgroundThrottling(true);
  1537. });
  1538. it('does not crash when called via BrowserWindow', () => {
  1539. const w = new BrowserWindow({ show: false });
  1540. (w as any).setBackgroundThrottling(true);
  1541. });
  1542. it('does not crash when disallowing', () => {
  1543. const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } });
  1544. w.webContents.setBackgroundThrottling(false);
  1545. });
  1546. });
  1547. describe('getBackgroundThrottling()', () => {
  1548. afterEach(closeAllWindows);
  1549. it('works via getter', () => {
  1550. const w = new BrowserWindow({ show: false });
  1551. w.webContents.setBackgroundThrottling(false);
  1552. expect(w.webContents.getBackgroundThrottling()).to.equal(false);
  1553. w.webContents.setBackgroundThrottling(true);
  1554. expect(w.webContents.getBackgroundThrottling()).to.equal(true);
  1555. });
  1556. it('works via property', () => {
  1557. const w = new BrowserWindow({ show: false });
  1558. w.webContents.backgroundThrottling = false;
  1559. expect(w.webContents.backgroundThrottling).to.equal(false);
  1560. w.webContents.backgroundThrottling = true;
  1561. expect(w.webContents.backgroundThrottling).to.equal(true);
  1562. });
  1563. it('works via BrowserWindow', () => {
  1564. const w = new BrowserWindow({ show: false });
  1565. (w as any).setBackgroundThrottling(false);
  1566. expect((w as any).getBackgroundThrottling()).to.equal(false);
  1567. (w as any).setBackgroundThrottling(true);
  1568. expect((w as any).getBackgroundThrottling()).to.equal(true);
  1569. });
  1570. });
  1571. ifdescribe(features.isPrintingEnabled())('getPrinters()', () => {
  1572. afterEach(closeAllWindows);
  1573. it('can get printer list', async () => {
  1574. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1575. await w.loadURL('about:blank');
  1576. const printers = w.webContents.getPrinters();
  1577. expect(printers).to.be.an('array');
  1578. });
  1579. });
  1580. ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => {
  1581. afterEach(closeAllWindows);
  1582. it('can get printer list', async () => {
  1583. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1584. await w.loadURL('about:blank');
  1585. const printers = await w.webContents.getPrintersAsync();
  1586. expect(printers).to.be.an('array');
  1587. });
  1588. });
  1589. ifdescribe(features.isPrintingEnabled())('printToPDF()', () => {
  1590. let w: BrowserWindow;
  1591. beforeEach(async () => {
  1592. w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1593. await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
  1594. });
  1595. afterEach(closeAllWindows);
  1596. it('rejects on incorrectly typed parameters', async () => {
  1597. const badTypes = {
  1598. landscape: [],
  1599. displayHeaderFooter: '123',
  1600. printBackground: 2,
  1601. scale: 'not-a-number',
  1602. pageSize: 'IAmAPageSize',
  1603. margins: 'terrible',
  1604. pageRanges: { oops: 'im-not-the-right-key' },
  1605. headerTemplate: [1, 2, 3],
  1606. footerTemplate: [4, 5, 6],
  1607. preferCSSPageSize: 'no'
  1608. };
  1609. // These will hard crash in Chromium unless we type-check
  1610. for (const [key, value] of Object.entries(badTypes)) {
  1611. const param = { [key]: value };
  1612. await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected();
  1613. }
  1614. });
  1615. it('can print to PDF', async () => {
  1616. const data = await w.webContents.printToPDF({});
  1617. expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
  1618. });
  1619. it('does not crash when called multiple times in parallel', async () => {
  1620. const promises = [];
  1621. for (let i = 0; i < 3; i++) {
  1622. promises.push(w.webContents.printToPDF({}));
  1623. }
  1624. const results = await Promise.all(promises);
  1625. for (const data of results) {
  1626. expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
  1627. }
  1628. });
  1629. it('does not crash when called multiple times in sequence', async () => {
  1630. const results = [];
  1631. for (let i = 0; i < 3; i++) {
  1632. const result = await w.webContents.printToPDF({});
  1633. results.push(result);
  1634. }
  1635. for (const data of results) {
  1636. expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
  1637. }
  1638. });
  1639. describe('using a large document', () => {
  1640. beforeEach(async () => {
  1641. w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1642. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf.html'));
  1643. });
  1644. afterEach(closeAllWindows);
  1645. it('respects custom settings', async () => {
  1646. const data = await w.webContents.printToPDF({
  1647. pageRanges: '1-3',
  1648. landscape: true
  1649. });
  1650. const doc = await pdfjs.getDocument(data).promise;
  1651. // Check that correct # of pages are rendered.
  1652. expect(doc.numPages).to.equal(3);
  1653. // Check that PDF is generated in landscape mode.
  1654. const firstPage = await doc.getPage(1);
  1655. const { width, height } = firstPage.getViewport({ scale: 100 });
  1656. expect(width).to.be.greaterThan(height);
  1657. });
  1658. });
  1659. });
  1660. describe('PictureInPicture video', () => {
  1661. afterEach(closeAllWindows);
  1662. it('works as expected', async function () {
  1663. const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  1664. await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html'));
  1665. if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) {
  1666. this.skip();
  1667. }
  1668. const result = await w.webContents.executeJavaScript(
  1669. `runTest(${features.isPictureInPictureEnabled()})`, true);
  1670. expect(result).to.be.true();
  1671. });
  1672. });
  1673. describe('Shared Workers', () => {
  1674. afterEach(closeAllWindows);
  1675. it('can get multiple shared workers', async () => {
  1676. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1677. const ready = emittedOnce(ipcMain, 'ready');
  1678. w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
  1679. await ready;
  1680. const sharedWorkers = w.webContents.getAllSharedWorkers();
  1681. expect(sharedWorkers).to.have.lengthOf(2);
  1682. expect(sharedWorkers[0].url).to.contain('shared-worker');
  1683. expect(sharedWorkers[1].url).to.contain('shared-worker');
  1684. });
  1685. it('can inspect a specific shared worker', async () => {
  1686. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1687. const ready = emittedOnce(ipcMain, 'ready');
  1688. w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
  1689. await ready;
  1690. const sharedWorkers = w.webContents.getAllSharedWorkers();
  1691. const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened');
  1692. w.webContents.inspectSharedWorkerById(sharedWorkers[0].id);
  1693. await devtoolsOpened;
  1694. const devtoolsClosed = emittedOnce(w.webContents, 'devtools-closed');
  1695. w.webContents.closeDevTools();
  1696. await devtoolsClosed;
  1697. });
  1698. });
  1699. describe('login event', () => {
  1700. afterEach(closeAllWindows);
  1701. let server: http.Server;
  1702. let serverUrl: string;
  1703. let serverPort: number;
  1704. let proxyServer: http.Server;
  1705. let proxyServerPort: number;
  1706. before((done) => {
  1707. server = http.createServer((request, response) => {
  1708. if (request.url === '/no-auth') {
  1709. return response.end('ok');
  1710. }
  1711. if (request.headers.authorization) {
  1712. response.writeHead(200, { 'Content-type': 'text/plain' });
  1713. return response.end(request.headers.authorization);
  1714. }
  1715. response
  1716. .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
  1717. .end('401');
  1718. }).listen(0, '127.0.0.1', () => {
  1719. serverPort = (server.address() as AddressInfo).port;
  1720. serverUrl = `http://127.0.0.1:${serverPort}`;
  1721. done();
  1722. });
  1723. });
  1724. before((done) => {
  1725. proxyServer = http.createServer((request, response) => {
  1726. if (request.headers['proxy-authorization']) {
  1727. response.writeHead(200, { 'Content-type': 'text/plain' });
  1728. return response.end(request.headers['proxy-authorization']);
  1729. }
  1730. response
  1731. .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' })
  1732. .end();
  1733. }).listen(0, '127.0.0.1', () => {
  1734. proxyServerPort = (proxyServer.address() as AddressInfo).port;
  1735. done();
  1736. });
  1737. });
  1738. afterEach(async () => {
  1739. await session.defaultSession.clearAuthCache();
  1740. });
  1741. after(() => {
  1742. server.close();
  1743. proxyServer.close();
  1744. });
  1745. it('is emitted when navigating', async () => {
  1746. const [user, pass] = ['user', 'pass'];
  1747. const w = new BrowserWindow({ show: false });
  1748. let eventRequest: any;
  1749. let eventAuthInfo: any;
  1750. w.webContents.on('login', (event, request, authInfo, cb) => {
  1751. eventRequest = request;
  1752. eventAuthInfo = authInfo;
  1753. event.preventDefault();
  1754. cb(user, pass);
  1755. });
  1756. await w.loadURL(serverUrl);
  1757. const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
  1758. expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
  1759. expect(eventRequest.url).to.equal(serverUrl + '/');
  1760. expect(eventAuthInfo.isProxy).to.be.false();
  1761. expect(eventAuthInfo.scheme).to.equal('basic');
  1762. expect(eventAuthInfo.host).to.equal('127.0.0.1');
  1763. expect(eventAuthInfo.port).to.equal(serverPort);
  1764. expect(eventAuthInfo.realm).to.equal('Foo');
  1765. });
  1766. it('is emitted when a proxy requests authorization', async () => {
  1767. const customSession = session.fromPartition(`${Math.random()}`);
  1768. await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' });
  1769. const [user, pass] = ['user', 'pass'];
  1770. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  1771. let eventRequest: any;
  1772. let eventAuthInfo: any;
  1773. w.webContents.on('login', (event, request, authInfo, cb) => {
  1774. eventRequest = request;
  1775. eventAuthInfo = authInfo;
  1776. event.preventDefault();
  1777. cb(user, pass);
  1778. });
  1779. await w.loadURL(`${serverUrl}/no-auth`);
  1780. const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
  1781. expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
  1782. expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`);
  1783. expect(eventAuthInfo.isProxy).to.be.true();
  1784. expect(eventAuthInfo.scheme).to.equal('basic');
  1785. expect(eventAuthInfo.host).to.equal('127.0.0.1');
  1786. expect(eventAuthInfo.port).to.equal(proxyServerPort);
  1787. expect(eventAuthInfo.realm).to.equal('Foo');
  1788. });
  1789. it('cancels authentication when callback is called with no arguments', async () => {
  1790. const w = new BrowserWindow({ show: false });
  1791. w.webContents.on('login', (event, request, authInfo, cb) => {
  1792. event.preventDefault();
  1793. cb();
  1794. });
  1795. await w.loadURL(serverUrl);
  1796. const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
  1797. expect(body).to.equal('401');
  1798. });
  1799. });
  1800. describe('page-title-updated event', () => {
  1801. afterEach(closeAllWindows);
  1802. it('is emitted with a full title for pages with no navigation', async () => {
  1803. const bw = new BrowserWindow({ show: false });
  1804. await bw.loadURL('about:blank');
  1805. bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null');
  1806. const [, child] = await emittedOnce(app, 'web-contents-created');
  1807. bw.webContents.executeJavaScript('child.document.title = "new title"');
  1808. const [, title] = await emittedOnce(child, 'page-title-updated');
  1809. expect(title).to.equal('new title');
  1810. });
  1811. });
  1812. describe('crashed event', () => {
  1813. it('does not crash main process when destroying WebContents in it', (done) => {
  1814. const contents = (webContents as any).create({ nodeIntegration: true });
  1815. contents.once('crashed', () => {
  1816. contents.destroy();
  1817. done();
  1818. });
  1819. contents.loadURL('about:blank').then(() => contents.forcefullyCrashRenderer());
  1820. });
  1821. });
  1822. describe('context-menu event', () => {
  1823. afterEach(closeAllWindows);
  1824. it('emits when right-clicked in page', async () => {
  1825. const w = new BrowserWindow({ show: false });
  1826. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
  1827. const promise = emittedOnce(w.webContents, 'context-menu');
  1828. // Simulate right-click to create context-menu event.
  1829. const opts = { x: 0, y: 0, button: 'right' as any };
  1830. w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' });
  1831. w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' });
  1832. const [, params] = await promise;
  1833. expect(params.pageURL).to.equal(w.webContents.getURL());
  1834. expect(params.frame).to.be.an('object');
  1835. expect(params.x).to.be.a('number');
  1836. expect(params.y).to.be.a('number');
  1837. });
  1838. });
  1839. });