chromium-spec.ts 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  1. import { expect } from 'chai';
  2. import { BrowserWindow, WebContents, session, ipcMain, app, protocol, webContents } from 'electron/main';
  3. import { emittedOnce } from './events-helpers';
  4. import { closeAllWindows } from './window-helpers';
  5. import * as https from 'https';
  6. import * as http from 'http';
  7. import * as path from 'path';
  8. import * as fs from 'fs';
  9. import * as url from 'url';
  10. import * as ChildProcess from 'child_process';
  11. import { EventEmitter } from 'events';
  12. import { promisify } from 'util';
  13. import { ifit, ifdescribe, delay, defer } from './spec-helpers';
  14. import { AddressInfo } from 'net';
  15. import { PipeTransport } from './pipe-transport';
  16. const features = process._linkedBinding('electron_common_features');
  17. const fixturesPath = path.resolve(__dirname, '..', 'spec', 'fixtures');
  18. describe('reporting api', () => {
  19. // TODO(nornagon): this started failing a lot on CI. Figure out why and fix
  20. // it.
  21. it.skip('sends a report for a deprecation', async () => {
  22. const reports = new EventEmitter();
  23. // The Reporting API only works on https with valid certs. To dodge having
  24. // to set up a trusted certificate, hack the validator.
  25. session.defaultSession.setCertificateVerifyProc((req, cb) => {
  26. cb(0);
  27. });
  28. const certPath = path.join(fixturesPath, 'certificates');
  29. const options = {
  30. key: fs.readFileSync(path.join(certPath, 'server.key')),
  31. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  32. ca: [
  33. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  34. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  35. ],
  36. requestCert: true,
  37. rejectUnauthorized: false
  38. };
  39. const server = https.createServer(options, (req, res) => {
  40. if (req.url === '/report') {
  41. let data = '';
  42. req.on('data', (d) => { data += d.toString('utf-8'); });
  43. req.on('end', () => {
  44. reports.emit('report', JSON.parse(data));
  45. });
  46. }
  47. res.setHeader('Report-To', JSON.stringify({
  48. group: 'default',
  49. max_age: 120,
  50. endpoints: [{ url: `https://localhost:${(server.address() as any).port}/report` }]
  51. }));
  52. res.setHeader('Content-Type', 'text/html');
  53. // using the deprecated `webkitRequestAnimationFrame` will trigger a
  54. // "deprecation" report.
  55. res.end('<script>webkitRequestAnimationFrame(() => {})</script>');
  56. });
  57. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  58. const bw = new BrowserWindow({
  59. show: false
  60. });
  61. try {
  62. const reportGenerated = emittedOnce(reports, 'report');
  63. const url = `https://localhost:${(server.address() as any).port}/a`;
  64. await bw.loadURL(url);
  65. const [report] = await reportGenerated;
  66. expect(report).to.be.an('array');
  67. expect(report[0].type).to.equal('deprecation');
  68. expect(report[0].url).to.equal(url);
  69. expect(report[0].body.id).to.equal('PrefixedRequestAnimationFrame');
  70. } finally {
  71. bw.destroy();
  72. server.close();
  73. }
  74. });
  75. });
  76. describe('window.postMessage', () => {
  77. afterEach(async () => {
  78. await closeAllWindows();
  79. });
  80. for (const nativeWindowOpen of [true, false]) {
  81. describe(`when nativeWindowOpen: ${nativeWindowOpen}`, () => {
  82. it('sets the source and origin correctly', async () => {
  83. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nativeWindowOpen } });
  84. w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`);
  85. const [, message] = await emittedOnce(ipcMain, 'complete');
  86. expect(message.data).to.equal('testing');
  87. expect(message.origin).to.equal('file://');
  88. expect(message.sourceEqualsOpener).to.equal(true);
  89. expect(message.eventOrigin).to.equal('file://');
  90. });
  91. });
  92. }
  93. });
  94. describe('focus handling', () => {
  95. let webviewContents: WebContents = null as unknown as WebContents;
  96. let w: BrowserWindow = null as unknown as BrowserWindow;
  97. beforeEach(async () => {
  98. w = new BrowserWindow({
  99. show: true,
  100. webPreferences: {
  101. nodeIntegration: true,
  102. webviewTag: true
  103. }
  104. });
  105. const webviewReady = emittedOnce(w.webContents, 'did-attach-webview');
  106. await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html'));
  107. const [, wvContents] = await webviewReady;
  108. webviewContents = wvContents;
  109. await emittedOnce(webviewContents, 'did-finish-load');
  110. w.focus();
  111. });
  112. afterEach(() => {
  113. webviewContents = null as unknown as WebContents;
  114. w.destroy();
  115. w = null as unknown as BrowserWindow;
  116. });
  117. const expectFocusChange = async () => {
  118. const [, focusedElementId] = await emittedOnce(ipcMain, 'focus-changed');
  119. return focusedElementId;
  120. };
  121. describe('a TAB press', () => {
  122. const tabPressEvent: any = {
  123. type: 'keyDown',
  124. keyCode: 'Tab'
  125. };
  126. it('moves focus to the next focusable item', async () => {
  127. let focusChange = expectFocusChange();
  128. w.webContents.sendInputEvent(tabPressEvent);
  129. let focusedElementId = await focusChange;
  130. expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`);
  131. focusChange = expectFocusChange();
  132. w.webContents.sendInputEvent(tabPressEvent);
  133. focusedElementId = await focusChange;
  134. expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
  135. focusChange = expectFocusChange();
  136. w.webContents.sendInputEvent(tabPressEvent);
  137. focusedElementId = await focusChange;
  138. expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
  139. focusChange = expectFocusChange();
  140. webviewContents.sendInputEvent(tabPressEvent);
  141. focusedElementId = await focusChange;
  142. expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
  143. focusChange = expectFocusChange();
  144. webviewContents.sendInputEvent(tabPressEvent);
  145. focusedElementId = await focusChange;
  146. expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`);
  147. focusChange = expectFocusChange();
  148. w.webContents.sendInputEvent(tabPressEvent);
  149. focusedElementId = await focusChange;
  150. expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`);
  151. });
  152. });
  153. describe('a SHIFT + TAB press', () => {
  154. const shiftTabPressEvent: any = {
  155. type: 'keyDown',
  156. modifiers: ['Shift'],
  157. keyCode: 'Tab'
  158. };
  159. it('moves focus to the previous focusable item', async () => {
  160. let focusChange = expectFocusChange();
  161. w.webContents.sendInputEvent(shiftTabPressEvent);
  162. let focusedElementId = await focusChange;
  163. expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`);
  164. focusChange = expectFocusChange();
  165. w.webContents.sendInputEvent(shiftTabPressEvent);
  166. focusedElementId = await focusChange;
  167. expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
  168. focusChange = expectFocusChange();
  169. webviewContents.sendInputEvent(shiftTabPressEvent);
  170. focusedElementId = await focusChange;
  171. expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
  172. focusChange = expectFocusChange();
  173. webviewContents.sendInputEvent(shiftTabPressEvent);
  174. focusedElementId = await focusChange;
  175. expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
  176. focusChange = expectFocusChange();
  177. w.webContents.sendInputEvent(shiftTabPressEvent);
  178. focusedElementId = await focusChange;
  179. expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`);
  180. focusChange = expectFocusChange();
  181. w.webContents.sendInputEvent(shiftTabPressEvent);
  182. focusedElementId = await focusChange;
  183. expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`);
  184. });
  185. });
  186. });
  187. describe('web security', () => {
  188. afterEach(closeAllWindows);
  189. let server: http.Server;
  190. let serverUrl: string;
  191. before(async () => {
  192. server = http.createServer((req, res) => {
  193. res.setHeader('Content-Type', 'text/html');
  194. res.end('<body>');
  195. });
  196. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  197. serverUrl = `http://localhost:${(server.address() as any).port}`;
  198. });
  199. after(() => {
  200. server.close();
  201. });
  202. it('engages CORB when web security is not disabled', async () => {
  203. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true } });
  204. const p = emittedOnce(ipcMain, 'success');
  205. await w.loadURL(`data:text/html,<script>
  206. const s = document.createElement('script')
  207. s.src = "${serverUrl}"
  208. // The script will load successfully but its body will be emptied out
  209. // by CORB, so we don't expect a syntax error.
  210. s.onload = () => { require('electron').ipcRenderer.send('success') }
  211. document.documentElement.appendChild(s)
  212. </script>`);
  213. await p;
  214. });
  215. it('bypasses CORB when web security is disabled', async () => {
  216. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true } });
  217. const p = emittedOnce(ipcMain, 'success');
  218. await w.loadURL(`data:text/html,
  219. <script>
  220. window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) }
  221. </script>
  222. <script src="${serverUrl}"></script>`);
  223. await p;
  224. });
  225. it('engages CORS when web security is not disabled', async () => {
  226. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true } });
  227. const p = emittedOnce(ipcMain, 'response');
  228. await w.loadURL(`data:text/html,<script>
  229. (async function() {
  230. try {
  231. await fetch('${serverUrl}');
  232. require('electron').ipcRenderer.send('response', 'passed');
  233. } catch {
  234. require('electron').ipcRenderer.send('response', 'failed');
  235. }
  236. })();
  237. </script>`);
  238. const [, response] = await p;
  239. expect(response).to.equal('failed');
  240. });
  241. it('bypasses CORS when web security is disabled', async () => {
  242. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true } });
  243. const p = emittedOnce(ipcMain, 'response');
  244. await w.loadURL(`data:text/html,<script>
  245. (async function() {
  246. try {
  247. await fetch('${serverUrl}');
  248. require('electron').ipcRenderer.send('response', 'passed');
  249. } catch {
  250. require('electron').ipcRenderer.send('response', 'failed');
  251. }
  252. })();
  253. </script>`);
  254. const [, response] = await p;
  255. expect(response).to.equal('passed');
  256. });
  257. it('does not crash when multiple WebContent are created with web security disabled', () => {
  258. const options = { show: false, webPreferences: { webSecurity: false } };
  259. const w1 = new BrowserWindow(options);
  260. w1.loadURL(serverUrl);
  261. const w2 = new BrowserWindow(options);
  262. w2.loadURL(serverUrl);
  263. });
  264. });
  265. describe('command line switches', () => {
  266. let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
  267. afterEach(() => {
  268. if (appProcess && !appProcess.killed) {
  269. appProcess.kill();
  270. appProcess = undefined;
  271. }
  272. });
  273. describe('--lang switch', () => {
  274. const currentLocale = app.getLocale();
  275. const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
  276. const appPath = path.join(fixturesPath, 'api', 'locale-check');
  277. const args = [appPath, `--set-lang=${locale}`];
  278. if (printEnv) {
  279. args.push('--print-env');
  280. }
  281. appProcess = ChildProcess.spawn(process.execPath, args);
  282. let output = '';
  283. appProcess.stdout.on('data', (data) => { output += data; });
  284. await emittedOnce(appProcess.stdout, 'end');
  285. output = output.replace(/(\r\n|\n|\r)/gm, '');
  286. expect(output).to.equal(result);
  287. };
  288. it('should set the locale', async () => testLocale('fr', 'fr'));
  289. it('should not set an invalid locale', async () => testLocale('asdfkl', currentLocale));
  290. const lcAll = String(process.env.LC_ALL);
  291. ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
  292. // The LC_ALL env should not be set to DOM locale string.
  293. expect(lcAll).to.not.equal(app.getLocale());
  294. });
  295. ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
  296. ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
  297. ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
  298. });
  299. describe('--remote-debugging-pipe switch', () => {
  300. it('should expose CDP via pipe', async () => {
  301. const electronPath = process.execPath;
  302. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
  303. stdio: ['pipe', 'pipe', 'pipe', 'pipe', 'pipe']
  304. });
  305. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  306. const pipe = new PipeTransport(stdio[3], stdio[4]);
  307. const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
  308. pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
  309. const message = (await versionPromise) as any;
  310. expect(message.id).to.equal(1);
  311. expect(message.result.product).to.contain('Chrome');
  312. expect(message.result.userAgent).to.contain('Electron');
  313. });
  314. it('should override --remote-debugging-port switch', async () => {
  315. const electronPath = process.execPath;
  316. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], {
  317. stdio: ['pipe', 'pipe', 'pipe', 'pipe', 'pipe']
  318. });
  319. let stderr = '';
  320. appProcess.stderr.on('data', (data: string) => { stderr += data; });
  321. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  322. const pipe = new PipeTransport(stdio[3], stdio[4]);
  323. const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
  324. pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
  325. const message = (await versionPromise) as any;
  326. expect(message.id).to.equal(1);
  327. expect(stderr).to.not.include('DevTools listening on');
  328. });
  329. it('should shut down Electron upon Browser.close CDP command', async () => {
  330. const electronPath = process.execPath;
  331. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
  332. stdio: ['pipe', 'pipe', 'pipe', 'pipe', 'pipe']
  333. });
  334. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  335. const pipe = new PipeTransport(stdio[3], stdio[4]);
  336. pipe.send({ id: 1, method: 'Browser.close', params: {} });
  337. await new Promise(resolve => { appProcess!.on('exit', resolve); });
  338. });
  339. });
  340. describe('--remote-debugging-port switch', () => {
  341. it('should display the discovery page', (done) => {
  342. const electronPath = process.execPath;
  343. let output = '';
  344. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']);
  345. appProcess.stderr.on('data', (data) => {
  346. output += data;
  347. const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
  348. if (m) {
  349. appProcess!.stderr.removeAllListeners('data');
  350. const port = m[1];
  351. http.get(`http://127.0.0.1:${port}`, (res) => {
  352. try {
  353. expect(res.statusCode).to.eql(200);
  354. expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
  355. done();
  356. } catch (e) {
  357. done(e);
  358. } finally {
  359. res.destroy();
  360. }
  361. });
  362. }
  363. });
  364. });
  365. });
  366. });
  367. describe('chromium features', () => {
  368. afterEach(closeAllWindows);
  369. describe('accessing key names also used as Node.js module names', () => {
  370. it('does not crash', (done) => {
  371. const w = new BrowserWindow({ show: false });
  372. w.webContents.once('did-finish-load', () => { done(); });
  373. w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
  374. w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
  375. });
  376. });
  377. describe('loading jquery', () => {
  378. it('does not crash', (done) => {
  379. const w = new BrowserWindow({ show: false });
  380. w.webContents.once('did-finish-load', () => { done(); });
  381. w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
  382. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
  383. });
  384. });
  385. describe('navigator.languages', () => {
  386. it('should return the system locale only', async () => {
  387. const appLocale = app.getLocale();
  388. const w = new BrowserWindow({ show: false });
  389. await w.loadURL('about:blank');
  390. const languages = await w.webContents.executeJavaScript('navigator.languages');
  391. expect(languages.length).to.be.greaterThan(0);
  392. expect(languages).to.contain(appLocale);
  393. });
  394. });
  395. describe('navigator.serviceWorker', () => {
  396. it('should register for file scheme', (done) => {
  397. const w = new BrowserWindow({
  398. show: false,
  399. webPreferences: {
  400. nodeIntegration: true,
  401. partition: 'sw-file-scheme-spec'
  402. }
  403. });
  404. w.webContents.on('ipc-message', (event, channel, message) => {
  405. if (channel === 'reload') {
  406. w.webContents.reload();
  407. } else if (channel === 'error') {
  408. done(message);
  409. } else if (channel === 'response') {
  410. expect(message).to.equal('Hello from serviceWorker!');
  411. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  412. storages: ['serviceworkers']
  413. }).then(() => done());
  414. }
  415. });
  416. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  417. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  418. });
  419. it('should register for intercepted file scheme', (done) => {
  420. const customSession = session.fromPartition('intercept-file');
  421. customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
  422. let file = url.parse(request.url).pathname!;
  423. if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
  424. const content = fs.readFileSync(path.normalize(file));
  425. const ext = path.extname(file);
  426. let type = 'text/html';
  427. if (ext === '.js') type = 'application/javascript';
  428. callback({ data: content, mimeType: type } as any);
  429. });
  430. const w = new BrowserWindow({
  431. show: false,
  432. webPreferences: {
  433. nodeIntegration: true,
  434. session: customSession
  435. }
  436. });
  437. w.webContents.on('ipc-message', (event, channel, message) => {
  438. if (channel === 'reload') {
  439. w.webContents.reload();
  440. } else if (channel === 'error') {
  441. done(`unexpected error : ${message}`);
  442. } else if (channel === 'response') {
  443. expect(message).to.equal('Hello from serviceWorker!');
  444. customSession.clearStorageData({
  445. storages: ['serviceworkers']
  446. }).then(() => {
  447. customSession.protocol.uninterceptProtocol('file');
  448. done();
  449. });
  450. }
  451. });
  452. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  453. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  454. });
  455. it('should not crash when nodeIntegration is enabled', (done) => {
  456. const w = new BrowserWindow({
  457. show: false,
  458. webPreferences: {
  459. nodeIntegration: true,
  460. nodeIntegrationInWorker: true,
  461. partition: 'sw-file-scheme-worker-spec'
  462. }
  463. });
  464. w.webContents.on('ipc-message', (event, channel, message) => {
  465. if (channel === 'reload') {
  466. w.webContents.reload();
  467. } else if (channel === 'error') {
  468. done(`unexpected error : ${message}`);
  469. } else if (channel === 'response') {
  470. expect(message).to.equal('Hello from serviceWorker!');
  471. session.fromPartition('sw-file-scheme-worker-spec').clearStorageData({
  472. storages: ['serviceworkers']
  473. }).then(() => done());
  474. }
  475. });
  476. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  477. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  478. });
  479. });
  480. describe('navigator.geolocation', () => {
  481. before(function () {
  482. if (!features.isFakeLocationProviderEnabled()) {
  483. return this.skip();
  484. }
  485. });
  486. it('returns error when permission is denied', async () => {
  487. const w = new BrowserWindow({
  488. show: false,
  489. webPreferences: {
  490. nodeIntegration: true,
  491. partition: 'geolocation-spec'
  492. }
  493. });
  494. const message = emittedOnce(w.webContents, 'ipc-message');
  495. w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
  496. if (permission === 'geolocation') {
  497. callback(false);
  498. } else {
  499. callback(true);
  500. }
  501. });
  502. w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
  503. const [, channel] = await message;
  504. expect(channel).to.equal('success', 'unexpected response from geolocation api');
  505. });
  506. });
  507. describe('form submit', () => {
  508. let server: http.Server;
  509. let serverUrl: string;
  510. before(async () => {
  511. server = http.createServer((req, res) => {
  512. let body = '';
  513. req.on('data', (chunk) => {
  514. body += chunk;
  515. });
  516. res.setHeader('Content-Type', 'application/json');
  517. req.on('end', () => {
  518. res.end(`body:${body}`);
  519. });
  520. });
  521. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  522. serverUrl = `http://localhost:${(server.address() as any).port}`;
  523. });
  524. after(async () => {
  525. server.close();
  526. await closeAllWindows();
  527. });
  528. [true, false].forEach((isSandboxEnabled) =>
  529. describe(`sandbox=${isSandboxEnabled}`, () => {
  530. it('posts data in the same window', async () => {
  531. const w = new BrowserWindow({
  532. show: false,
  533. webPreferences: {
  534. sandbox: isSandboxEnabled
  535. }
  536. });
  537. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  538. const loadPromise = emittedOnce(w.webContents, 'did-finish-load');
  539. w.webContents.executeJavaScript(`
  540. const form = document.querySelector('form')
  541. form.action = '${serverUrl}';
  542. form.submit();
  543. `);
  544. await loadPromise;
  545. const res = await w.webContents.executeJavaScript('document.body.innerText');
  546. expect(res).to.equal('body:greeting=hello');
  547. });
  548. it('posts data to a new window with target=_blank', async () => {
  549. const w = new BrowserWindow({
  550. show: false,
  551. webPreferences: {
  552. sandbox: isSandboxEnabled
  553. }
  554. });
  555. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  556. const windowCreatedPromise = emittedOnce(app, 'browser-window-created');
  557. w.webContents.executeJavaScript(`
  558. const form = document.querySelector('form')
  559. form.action = '${serverUrl}';
  560. form.target = '_blank';
  561. form.submit();
  562. `);
  563. const [, newWin] = await windowCreatedPromise;
  564. const res = await newWin.webContents.executeJavaScript('document.body.innerText');
  565. expect(res).to.equal('body:greeting=hello');
  566. });
  567. })
  568. );
  569. });
  570. describe('window.open', () => {
  571. for (const show of [true, false]) {
  572. it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => {
  573. const w = new BrowserWindow({ show });
  574. // toggle visibility
  575. if (show) {
  576. w.hide();
  577. } else {
  578. w.show();
  579. }
  580. defer(() => { w.close(); });
  581. const newWindow = emittedOnce(w.webContents, 'new-window');
  582. w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
  583. const [,,,, options] = await newWindow;
  584. expect(options.show).to.equal(true);
  585. });
  586. }
  587. it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
  588. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  589. w.loadURL('about:blank');
  590. w.webContents.executeJavaScript(`
  591. b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no')
  592. `);
  593. const [, contents] = await emittedOnce(app, 'web-contents-created');
  594. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  595. expect(typeofProcessGlobal).to.equal('undefined');
  596. });
  597. it('disables JavaScript when it is disabled on the parent window', async () => {
  598. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  599. w.webContents.loadURL('about:blank');
  600. const windowUrl = require('url').format({
  601. pathname: `${fixturesPath}/pages/window-no-javascript.html`,
  602. protocol: 'file',
  603. slashes: true
  604. });
  605. w.webContents.executeJavaScript(`
  606. b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no')
  607. `);
  608. const [, contents] = await emittedOnce(app, 'web-contents-created');
  609. await emittedOnce(contents, 'did-finish-load');
  610. // Click link on page
  611. contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
  612. contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
  613. const [, window] = await emittedOnce(app, 'browser-window-created');
  614. const preferences = window.webContents.getLastWebPreferences();
  615. expect(preferences.javascript).to.be.false();
  616. });
  617. it('defines a window.location getter', async () => {
  618. let targetURL: string;
  619. if (process.platform === 'win32') {
  620. targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
  621. } else {
  622. targetURL = `file://${fixturesPath}/pages/base-page.html`;
  623. }
  624. const w = new BrowserWindow({ show: false });
  625. w.loadURL('about:blank');
  626. w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
  627. const [, window] = await emittedOnce(app, 'browser-window-created');
  628. await emittedOnce(window.webContents, 'did-finish-load');
  629. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
  630. });
  631. it('defines a window.location setter', async () => {
  632. const w = new BrowserWindow({ show: false });
  633. w.loadURL('about:blank');
  634. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  635. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  636. await emittedOnce(webContents, 'did-finish-load');
  637. // When it loads, redirect
  638. w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  639. await emittedOnce(webContents, 'did-finish-load');
  640. });
  641. it('defines a window.location.href setter', async () => {
  642. const w = new BrowserWindow({ show: false });
  643. w.loadURL('about:blank');
  644. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  645. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  646. await emittedOnce(webContents, 'did-finish-load');
  647. // When it loads, redirect
  648. w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  649. await emittedOnce(webContents, 'did-finish-load');
  650. });
  651. it('open a blank page when no URL is specified', async () => {
  652. const w = new BrowserWindow({ show: false });
  653. w.loadURL('about:blank');
  654. w.webContents.executeJavaScript('{ b = window.open(); null }');
  655. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  656. await emittedOnce(webContents, 'did-finish-load');
  657. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  658. });
  659. it('open a blank page when an empty URL is specified', async () => {
  660. const w = new BrowserWindow({ show: false });
  661. w.loadURL('about:blank');
  662. w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
  663. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  664. await emittedOnce(webContents, 'did-finish-load');
  665. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  666. });
  667. it('sets the window title to the specified frameName', async () => {
  668. const w = new BrowserWindow({ show: false });
  669. w.loadURL('about:blank');
  670. w.webContents.executeJavaScript('{ b = window.open(\'\', \'hello\'); null }');
  671. const [, window] = await emittedOnce(app, 'browser-window-created');
  672. expect(window.getTitle()).to.equal('hello');
  673. });
  674. it('does not throw an exception when the frameName is a built-in object property', async () => {
  675. const w = new BrowserWindow({ show: false });
  676. w.loadURL('about:blank');
  677. w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
  678. const [, window] = await emittedOnce(app, 'browser-window-created');
  679. expect(window.getTitle()).to.equal('__proto__');
  680. });
  681. it('denies custom open when nativeWindowOpen: true', async () => {
  682. const w = new BrowserWindow({
  683. show: false,
  684. webPreferences: {
  685. contextIsolation: false,
  686. nodeIntegration: true,
  687. nativeWindowOpen: true
  688. }
  689. });
  690. w.loadURL('about:blank');
  691. const previousListeners = process.listeners('uncaughtException');
  692. process.removeAllListeners('uncaughtException');
  693. try {
  694. const uncaughtException = new Promise<Error>(resolve => {
  695. process.once('uncaughtException', resolve);
  696. });
  697. expect(await w.webContents.executeJavaScript(`(${function () {
  698. const { ipc } = process._linkedBinding('electron_renderer_ipc');
  699. return ipc.sendSync(true, 'GUEST_WINDOW_MANAGER_WINDOW_OPEN', ['', '', '']);
  700. }})()`)).to.be.null();
  701. const exception = await uncaughtException;
  702. expect(exception.message).to.match(/denied: expected native window\.open/);
  703. } finally {
  704. previousListeners.forEach(l => process.on('uncaughtException', l));
  705. }
  706. });
  707. });
  708. describe('window.opener', () => {
  709. it('is null for main window', async () => {
  710. const w = new BrowserWindow({
  711. show: false,
  712. webPreferences: {
  713. nodeIntegration: true
  714. }
  715. });
  716. w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
  717. const [, channel, opener] = await emittedOnce(w.webContents, 'ipc-message');
  718. expect(channel).to.equal('opener');
  719. expect(opener).to.equal(null);
  720. });
  721. });
  722. describe('navigator.mediaDevices', () => {
  723. afterEach(closeAllWindows);
  724. afterEach(() => {
  725. session.defaultSession.setPermissionCheckHandler(null);
  726. });
  727. it('can return labels of enumerated devices', async () => {
  728. const w = new BrowserWindow({ show: false });
  729. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  730. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  731. expect(labels.some((l: any) => l)).to.be.true();
  732. });
  733. it('does not return labels of enumerated devices when permission denied', async () => {
  734. session.defaultSession.setPermissionCheckHandler(() => false);
  735. const w = new BrowserWindow({ show: false });
  736. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  737. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  738. expect(labels.some((l: any) => l)).to.be.false();
  739. });
  740. it('returns the same device ids across reloads', async () => {
  741. const ses = session.fromPartition('persist:media-device-id');
  742. const w = new BrowserWindow({
  743. show: false,
  744. webPreferences: {
  745. nodeIntegration: true,
  746. session: ses
  747. }
  748. });
  749. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  750. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  751. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  752. expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
  753. });
  754. it('can return new device id when cookie storage is cleared', async () => {
  755. const ses = session.fromPartition('persist:media-device-id');
  756. const w = new BrowserWindow({
  757. show: false,
  758. webPreferences: {
  759. nodeIntegration: true,
  760. session: ses
  761. }
  762. });
  763. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  764. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  765. await ses.clearStorageData({ storages: ['cookies'] });
  766. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  767. expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
  768. });
  769. });
  770. describe('window.opener access', () => {
  771. const scheme = 'app';
  772. const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
  773. const httpUrl1 = `${scheme}://origin1`;
  774. const httpUrl2 = `${scheme}://origin2`;
  775. const fileBlank = `file://${fixturesPath}/pages/blank.html`;
  776. const httpBlank = `${scheme}://origin1/blank`;
  777. const table = [
  778. { parent: fileBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: false },
  779. { parent: fileBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: false },
  780. { parent: fileBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  781. { parent: fileBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: false },
  782. { parent: httpBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: false },
  783. // {parent: httpBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: false}, // can't window.open()
  784. { parent: httpBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  785. // {parent: httpBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: false}, // can't window.open()
  786. // NB. this is different from Chrome's behavior, which isolates file: urls from each other
  787. { parent: fileBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: true },
  788. { parent: fileBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: true },
  789. { parent: fileBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  790. { parent: fileBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: true },
  791. { parent: httpBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: true },
  792. { parent: httpBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: true },
  793. { parent: httpBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  794. { parent: httpBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: true },
  795. { parent: httpBlank, child: httpUrl2, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: false },
  796. { parent: httpBlank, child: httpUrl2, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: false },
  797. { parent: httpBlank, child: httpUrl2, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  798. { parent: httpBlank, child: httpUrl2, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: false }
  799. ];
  800. const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
  801. before(() => {
  802. protocol.registerFileProtocol(scheme, (request, callback) => {
  803. if (request.url.includes('blank')) {
  804. callback(`${fixturesPath}/pages/blank.html`);
  805. } else {
  806. callback(`${fixturesPath}/pages/window-opener-location.html`);
  807. }
  808. });
  809. });
  810. after(() => {
  811. protocol.unregisterProtocol(scheme);
  812. });
  813. afterEach(closeAllWindows);
  814. describe('when opened from main window', () => {
  815. for (const { parent, child, nodeIntegration, nativeWindowOpen, openerAccessible } of table) {
  816. for (const sandboxPopup of [false, true]) {
  817. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} nativeWindowOpen=${nativeWindowOpen} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  818. it(description, async () => {
  819. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, nativeWindowOpen } });
  820. w.webContents.setWindowOpenHandler(() => ({
  821. action: 'allow',
  822. overrideBrowserWindowOptions: {
  823. webPreferences: {
  824. sandbox: sandboxPopup
  825. }
  826. }
  827. }));
  828. await w.loadURL(parent);
  829. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
  830. window.addEventListener('message', function f(e) {
  831. resolve(e.data)
  832. })
  833. window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
  834. })`);
  835. if (openerAccessible) {
  836. expect(childOpenerLocation).to.be.a('string');
  837. } else {
  838. expect(childOpenerLocation).to.be.null();
  839. }
  840. });
  841. }
  842. }
  843. });
  844. describe('when opened from <webview>', () => {
  845. for (const { parent, child, nodeIntegration, nativeWindowOpen, openerAccessible } of table) {
  846. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} nativeWindowOpen=${nativeWindowOpen}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  847. // WebView erroneously allows access to the parent window when nativeWindowOpen is false.
  848. const skip = !nativeWindowOpen && !openerAccessible;
  849. ifit(!skip)(description, async () => {
  850. // This test involves three contexts:
  851. // 1. The root BrowserWindow in which the test is run,
  852. // 2. A <webview> belonging to the root window,
  853. // 3. A window opened by calling window.open() from within the <webview>.
  854. // We are testing whether context (3) can access context (2) under various conditions.
  855. // This is context (1), the base window for the test.
  856. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true } });
  857. await w.loadURL('about:blank');
  858. const parentCode = `new Promise((resolve) => {
  859. // This is context (3), a child window of the WebView.
  860. const child = window.open(${JSON.stringify(child)}, "", "show=no")
  861. window.addEventListener("message", e => {
  862. resolve(e.data)
  863. })
  864. })`;
  865. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  866. // This is context (2), a WebView which will call window.open()
  867. const webview = new WebView()
  868. webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
  869. webview.setAttribute('webpreferences', 'nativeWindowOpen=${nativeWindowOpen ? 'yes' : 'no'}')
  870. webview.setAttribute('allowpopups', 'on')
  871. webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
  872. webview.addEventListener('dom-ready', async () => {
  873. webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
  874. })
  875. document.body.appendChild(webview)
  876. })`);
  877. if (openerAccessible) {
  878. expect(childOpenerLocation).to.be.a('string');
  879. } else {
  880. expect(childOpenerLocation).to.be.null();
  881. }
  882. });
  883. }
  884. });
  885. });
  886. describe('storage', () => {
  887. describe('custom non standard schemes', () => {
  888. const protocolName = 'storage';
  889. let contents: WebContents;
  890. before(() => {
  891. protocol.registerFileProtocol(protocolName, (request, callback) => {
  892. const parsedUrl = url.parse(request.url);
  893. let filename;
  894. switch (parsedUrl.pathname) {
  895. case '/localStorage' : filename = 'local_storage.html'; break;
  896. case '/sessionStorage' : filename = 'session_storage.html'; break;
  897. case '/WebSQL' : filename = 'web_sql.html'; break;
  898. case '/indexedDB' : filename = 'indexed_db.html'; break;
  899. case '/cookie' : filename = 'cookie.html'; break;
  900. default : filename = '';
  901. }
  902. callback({ path: `${fixturesPath}/pages/storage/${filename}` });
  903. });
  904. });
  905. after(() => {
  906. protocol.unregisterProtocol(protocolName);
  907. });
  908. beforeEach(() => {
  909. contents = (webContents as any).create({
  910. nodeIntegration: true
  911. });
  912. });
  913. afterEach(() => {
  914. (contents as any).destroy();
  915. contents = null as any;
  916. });
  917. it('cannot access localStorage', async () => {
  918. const response = emittedOnce(ipcMain, 'local-storage-response');
  919. contents.loadURL(protocolName + '://host/localStorage');
  920. const [, error] = await response;
  921. expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.');
  922. });
  923. it('cannot access sessionStorage', async () => {
  924. const response = emittedOnce(ipcMain, 'session-storage-response');
  925. contents.loadURL(`${protocolName}://host/sessionStorage`);
  926. const [, error] = await response;
  927. expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.');
  928. });
  929. it('cannot access WebSQL database', async () => {
  930. const response = emittedOnce(ipcMain, 'web-sql-response');
  931. contents.loadURL(`${protocolName}://host/WebSQL`);
  932. const [, error] = await response;
  933. expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.');
  934. });
  935. it('cannot access indexedDB', async () => {
  936. const response = emittedOnce(ipcMain, 'indexed-db-response');
  937. contents.loadURL(`${protocolName}://host/indexedDB`);
  938. const [, error] = await response;
  939. expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.');
  940. });
  941. it('cannot access cookie', async () => {
  942. const response = emittedOnce(ipcMain, 'cookie-response');
  943. contents.loadURL(`${protocolName}://host/cookie`);
  944. const [, error] = await response;
  945. expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.');
  946. });
  947. });
  948. describe('can be accessed', () => {
  949. let server: http.Server;
  950. let serverUrl: string;
  951. let serverCrossSiteUrl: string;
  952. before((done) => {
  953. server = http.createServer((req, res) => {
  954. const respond = () => {
  955. if (req.url === '/redirect-cross-site') {
  956. res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
  957. res.statusCode = 302;
  958. res.end();
  959. } else if (req.url === '/redirected') {
  960. res.end('<html><script>window.localStorage</script></html>');
  961. } else {
  962. res.end();
  963. }
  964. };
  965. setTimeout(respond, 0);
  966. });
  967. server.listen(0, '127.0.0.1', () => {
  968. serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  969. serverCrossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`;
  970. done();
  971. });
  972. });
  973. after(() => {
  974. server.close();
  975. server = null as any;
  976. });
  977. afterEach(closeAllWindows);
  978. const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
  979. it(testTitle, async () => {
  980. const w = new BrowserWindow({
  981. show: false,
  982. ...extraPreferences
  983. });
  984. let redirected = false;
  985. w.webContents.on('crashed', () => {
  986. expect.fail('renderer crashed / was killed');
  987. });
  988. w.webContents.on('did-redirect-navigation', (event, url) => {
  989. expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
  990. redirected = true;
  991. });
  992. await w.loadURL(`${serverUrl}/redirect-cross-site`);
  993. expect(redirected).to.be.true('didnt redirect');
  994. });
  995. };
  996. testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
  997. testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
  998. });
  999. describe('enableWebSQL webpreference', () => {
  1000. const standardScheme = (global as any).standardScheme;
  1001. const origin = `${standardScheme}://fake-host`;
  1002. const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
  1003. const sqlPartition = 'web-sql-preference-test';
  1004. const sqlSession = session.fromPartition(sqlPartition);
  1005. const securityError = 'An attempt was made to break through the security policy of the user agent.';
  1006. let contents: WebContents, w: BrowserWindow;
  1007. before(() => {
  1008. sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
  1009. callback({ path: filePath });
  1010. });
  1011. });
  1012. after(() => {
  1013. sqlSession.protocol.unregisterProtocol(standardScheme);
  1014. });
  1015. afterEach(async () => {
  1016. if (contents) {
  1017. (contents as any).destroy();
  1018. contents = null as any;
  1019. }
  1020. await closeAllWindows();
  1021. (w as any) = null;
  1022. });
  1023. it('default value allows websql', async () => {
  1024. contents = (webContents as any).create({
  1025. session: sqlSession,
  1026. nodeIntegration: true
  1027. });
  1028. contents.loadURL(origin);
  1029. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1030. expect(error).to.be.null();
  1031. });
  1032. it('when set to false can disallow websql', async () => {
  1033. contents = (webContents as any).create({
  1034. session: sqlSession,
  1035. nodeIntegration: true,
  1036. enableWebSQL: false
  1037. });
  1038. contents.loadURL(origin);
  1039. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1040. expect(error).to.equal(securityError);
  1041. });
  1042. it('when set to false does not disable indexedDB', async () => {
  1043. contents = (webContents as any).create({
  1044. session: sqlSession,
  1045. nodeIntegration: true,
  1046. enableWebSQL: false
  1047. });
  1048. contents.loadURL(origin);
  1049. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1050. expect(error).to.equal(securityError);
  1051. const dbName = 'random';
  1052. const result = await contents.executeJavaScript(`
  1053. new Promise((resolve, reject) => {
  1054. try {
  1055. let req = window.indexedDB.open('${dbName}');
  1056. req.onsuccess = (event) => {
  1057. let db = req.result;
  1058. resolve(db.name);
  1059. }
  1060. req.onerror = (event) => { resolve(event.target.code); }
  1061. } catch (e) {
  1062. resolve(e.message);
  1063. }
  1064. });
  1065. `);
  1066. expect(result).to.equal(dbName);
  1067. });
  1068. it('child webContents can override when the embedder has allowed websql', async () => {
  1069. w = new BrowserWindow({
  1070. show: false,
  1071. webPreferences: {
  1072. nodeIntegration: true,
  1073. webviewTag: true,
  1074. session: sqlSession
  1075. }
  1076. });
  1077. w.webContents.loadURL(origin);
  1078. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1079. expect(error).to.be.null();
  1080. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1081. await w.webContents.executeJavaScript(`
  1082. new Promise((resolve, reject) => {
  1083. const webview = new WebView();
  1084. webview.setAttribute('src', '${origin}');
  1085. webview.setAttribute('webpreferences', 'enableWebSQL=0');
  1086. webview.setAttribute('partition', '${sqlPartition}');
  1087. webview.setAttribute('nodeIntegration', 'on');
  1088. document.body.appendChild(webview);
  1089. webview.addEventListener('dom-ready', () => resolve());
  1090. });
  1091. `);
  1092. const [, childError] = await webviewResult;
  1093. expect(childError).to.equal(securityError);
  1094. });
  1095. it('child webContents cannot override when the embedder has disallowed websql', async () => {
  1096. w = new BrowserWindow({
  1097. show: false,
  1098. webPreferences: {
  1099. nodeIntegration: true,
  1100. enableWebSQL: false,
  1101. webviewTag: true,
  1102. session: sqlSession
  1103. }
  1104. });
  1105. w.webContents.loadURL('data:text/html,<html></html>');
  1106. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1107. await w.webContents.executeJavaScript(`
  1108. new Promise((resolve, reject) => {
  1109. const webview = new WebView();
  1110. webview.setAttribute('src', '${origin}');
  1111. webview.setAttribute('webpreferences', 'enableWebSQL=1');
  1112. webview.setAttribute('partition', '${sqlPartition}');
  1113. webview.setAttribute('nodeIntegration', 'on');
  1114. document.body.appendChild(webview);
  1115. webview.addEventListener('dom-ready', () => resolve());
  1116. });
  1117. `);
  1118. const [, childError] = await webviewResult;
  1119. expect(childError).to.equal(securityError);
  1120. });
  1121. it('child webContents can use websql when the embedder has allowed websql', async () => {
  1122. w = new BrowserWindow({
  1123. show: false,
  1124. webPreferences: {
  1125. nodeIntegration: true,
  1126. webviewTag: true,
  1127. session: sqlSession
  1128. }
  1129. });
  1130. w.webContents.loadURL(origin);
  1131. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1132. expect(error).to.be.null();
  1133. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1134. await w.webContents.executeJavaScript(`
  1135. new Promise((resolve, reject) => {
  1136. const webview = new WebView();
  1137. webview.setAttribute('src', '${origin}');
  1138. webview.setAttribute('webpreferences', 'enableWebSQL=1');
  1139. webview.setAttribute('partition', '${sqlPartition}');
  1140. webview.setAttribute('nodeIntegration', 'on');
  1141. document.body.appendChild(webview);
  1142. webview.addEventListener('dom-ready', () => resolve());
  1143. });
  1144. `);
  1145. const [, childError] = await webviewResult;
  1146. expect(childError).to.be.null();
  1147. });
  1148. });
  1149. });
  1150. ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
  1151. const pdfSource = url.format({
  1152. pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'),
  1153. protocol: 'file',
  1154. slashes: true
  1155. });
  1156. it('opens when loading a pdf resource as top level navigation', async () => {
  1157. const w = new BrowserWindow({ show: false });
  1158. w.loadURL(pdfSource);
  1159. const [, contents] = await emittedOnce(app, 'web-contents-created');
  1160. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1161. });
  1162. it('opens when loading a pdf resource in a iframe', async () => {
  1163. const w = new BrowserWindow({ show: false });
  1164. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
  1165. const [, contents] = await emittedOnce(app, 'web-contents-created');
  1166. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1167. });
  1168. });
  1169. describe('window.history', () => {
  1170. describe('window.history.pushState', () => {
  1171. it('should push state after calling history.pushState() from the same url', async () => {
  1172. const w = new BrowserWindow({ show: false });
  1173. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1174. // History should have current page by now.
  1175. expect((w.webContents as any).length()).to.equal(1);
  1176. const waitCommit = emittedOnce(w.webContents, 'navigation-entry-committed');
  1177. w.webContents.executeJavaScript('window.history.pushState({}, "")');
  1178. await waitCommit;
  1179. // Initial page + pushed state.
  1180. expect((w.webContents as any).length()).to.equal(2);
  1181. });
  1182. });
  1183. });
  1184. describe('chrome://media-internals', () => {
  1185. it('loads the page successfully', async () => {
  1186. const w = new BrowserWindow({ show: false });
  1187. w.loadURL('chrome://media-internals');
  1188. const pageExists = await w.webContents.executeJavaScript(
  1189. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1190. );
  1191. expect(pageExists).to.be.true();
  1192. });
  1193. });
  1194. describe('chrome://webrtc-internals', () => {
  1195. it('loads the page successfully', async () => {
  1196. const w = new BrowserWindow({ show: false });
  1197. w.loadURL('chrome://webrtc-internals');
  1198. const pageExists = await w.webContents.executeJavaScript(
  1199. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1200. );
  1201. expect(pageExists).to.be.true();
  1202. });
  1203. });
  1204. });
  1205. describe('font fallback', () => {
  1206. async function getRenderedFonts (html: string) {
  1207. const w = new BrowserWindow({ show: false });
  1208. try {
  1209. await w.loadURL(`data:text/html,${html}`);
  1210. w.webContents.debugger.attach();
  1211. const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
  1212. const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
  1213. await sendCommand('CSS.enable');
  1214. const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
  1215. return fonts;
  1216. } finally {
  1217. w.close();
  1218. }
  1219. }
  1220. it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
  1221. const html = '<body style="font-family: sans-serif">test</body>';
  1222. const fonts = await getRenderedFonts(html);
  1223. expect(fonts).to.be.an('array');
  1224. expect(fonts).to.have.length(1);
  1225. if (process.platform === 'win32') { expect(fonts[0].familyName).to.equal('Arial'); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Helvetica'); } else if (process.platform === 'linux') { expect(fonts[0].familyName).to.equal('DejaVu Sans'); } // I think this depends on the distro? We don't specify a default.
  1226. });
  1227. ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
  1228. const html = `
  1229. <html lang="ja-JP">
  1230. <head>
  1231. <meta charset="utf-8" />
  1232. </head>
  1233. <body style="font-family: sans-serif">test 智史</body>
  1234. </html>
  1235. `;
  1236. const fonts = await getRenderedFonts(html);
  1237. expect(fonts).to.be.an('array');
  1238. expect(fonts).to.have.length(1);
  1239. if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); }
  1240. });
  1241. });
  1242. describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
  1243. const fullscreenChildHtml = promisify(fs.readFile)(
  1244. path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
  1245. );
  1246. let w: BrowserWindow, server: http.Server;
  1247. before(() => {
  1248. server = http.createServer(async (_req, res) => {
  1249. res.writeHead(200, { 'Content-Type': 'text/html' });
  1250. res.write(await fullscreenChildHtml);
  1251. res.end();
  1252. });
  1253. server.listen(8989, '127.0.0.1');
  1254. });
  1255. beforeEach(() => {
  1256. w = new BrowserWindow({
  1257. show: true,
  1258. fullscreen: true,
  1259. webPreferences: {
  1260. nodeIntegration: true,
  1261. nodeIntegrationInSubFrames: true
  1262. }
  1263. });
  1264. });
  1265. afterEach(async () => {
  1266. await closeAllWindows()
  1267. ;(w as any) = null;
  1268. server.close();
  1269. });
  1270. it('can fullscreen from out-of-process iframes (OOPIFs)', async () => {
  1271. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  1272. const html =
  1273. '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>';
  1274. w.loadURL(`data:text/html,${html}`);
  1275. await fullscreenChange;
  1276. const fullscreenWidth = await w.webContents.executeJavaScript(
  1277. "document.querySelector('iframe').offsetWidth"
  1278. );
  1279. expect(fullscreenWidth > 0).to.be.true();
  1280. await w.webContents.executeJavaScript(
  1281. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  1282. );
  1283. await delay(500);
  1284. const width = await w.webContents.executeJavaScript(
  1285. "document.querySelector('iframe').offsetWidth"
  1286. );
  1287. expect(width).to.equal(0);
  1288. });
  1289. it('can fullscreen from in-process iframes', async () => {
  1290. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  1291. w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
  1292. await fullscreenChange;
  1293. const fullscreenWidth = await w.webContents.executeJavaScript(
  1294. "document.querySelector('iframe').offsetWidth"
  1295. );
  1296. expect(fullscreenWidth > 0).to.true();
  1297. await w.webContents.executeJavaScript('document.exitFullscreen()');
  1298. const width = await w.webContents.executeJavaScript(
  1299. "document.querySelector('iframe').offsetWidth"
  1300. );
  1301. expect(width).to.equal(0);
  1302. });
  1303. });
  1304. describe('navigator.serial', () => {
  1305. let w: BrowserWindow;
  1306. before(async () => {
  1307. w = new BrowserWindow({
  1308. show: false,
  1309. webPreferences: {
  1310. enableBlinkFeatures: 'Serial'
  1311. }
  1312. });
  1313. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1314. });
  1315. const getPorts: any = () => {
  1316. return w.webContents.executeJavaScript(`
  1317. navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
  1318. `, true);
  1319. };
  1320. after(closeAllWindows);
  1321. afterEach(() => {
  1322. session.defaultSession.setPermissionCheckHandler(null);
  1323. session.defaultSession.removeAllListeners('select-serial-port');
  1324. });
  1325. it('does not return a port if select-serial-port event is not defined', async () => {
  1326. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1327. const port = await getPorts();
  1328. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1329. });
  1330. it('does not return a port when permission denied', async () => {
  1331. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1332. callback(portList[0].portId);
  1333. });
  1334. session.defaultSession.setPermissionCheckHandler(() => false);
  1335. const port = await getPorts();
  1336. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1337. });
  1338. it('returns a port when select-serial-port event is defined', async () => {
  1339. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1340. callback(portList[0].portId);
  1341. });
  1342. const port = await getPorts();
  1343. expect(port).to.equal('[object SerialPort]');
  1344. });
  1345. });
  1346. describe('navigator.clipboard', () => {
  1347. let w: BrowserWindow;
  1348. before(async () => {
  1349. w = new BrowserWindow({
  1350. show: false,
  1351. webPreferences: {
  1352. enableBlinkFeatures: 'Serial'
  1353. }
  1354. });
  1355. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1356. });
  1357. const readClipboard: any = () => {
  1358. return w.webContents.executeJavaScript(`
  1359. navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
  1360. `, true);
  1361. };
  1362. after(closeAllWindows);
  1363. afterEach(() => {
  1364. session.defaultSession.setPermissionRequestHandler(null);
  1365. });
  1366. it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
  1367. const clipboard = await readClipboard();
  1368. expect(clipboard).to.not.equal('Read permission denied.');
  1369. });
  1370. it('returns an error when permission denied', async () => {
  1371. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  1372. if (permission === 'clipboard-read') {
  1373. callback(false);
  1374. } else {
  1375. callback(true);
  1376. }
  1377. });
  1378. const clipboard = await readClipboard();
  1379. expect(clipboard).to.equal('Read permission denied.');
  1380. });
  1381. it('returns clipboard contents when permission is granted', async () => {
  1382. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  1383. if (permission === 'clipboard-read') {
  1384. callback(true);
  1385. } else {
  1386. callback(false);
  1387. }
  1388. });
  1389. const clipboard = await readClipboard();
  1390. expect(clipboard).to.not.equal('Read permission denied.');
  1391. });
  1392. });