chromium-spec.ts 64 KB

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