api-web-contents-spec.ts 75 KB

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