chromium-spec.ts 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089
  1. import { expect } from 'chai';
  2. import { BrowserWindow, WebContents, webFrameMain, 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<void>(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, contextIsolation: false } });
  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. contextIsolation: false
  100. }
  101. });
  102. const webviewReady = emittedOnce(w.webContents, 'did-attach-webview');
  103. await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html'));
  104. const [, wvContents] = await webviewReady;
  105. webviewContents = wvContents;
  106. await emittedOnce(webviewContents, 'did-finish-load');
  107. w.focus();
  108. });
  109. afterEach(() => {
  110. webviewContents = null as unknown as WebContents;
  111. w.destroy();
  112. w = null as unknown as BrowserWindow;
  113. });
  114. const expectFocusChange = async () => {
  115. const [, focusedElementId] = await emittedOnce(ipcMain, 'focus-changed');
  116. return focusedElementId;
  117. };
  118. describe('a TAB press', () => {
  119. const tabPressEvent: any = {
  120. type: 'keyDown',
  121. keyCode: 'Tab'
  122. };
  123. it('moves focus to the next focusable item', async () => {
  124. let focusChange = expectFocusChange();
  125. w.webContents.sendInputEvent(tabPressEvent);
  126. let focusedElementId = await focusChange;
  127. expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`);
  128. focusChange = expectFocusChange();
  129. w.webContents.sendInputEvent(tabPressEvent);
  130. focusedElementId = await focusChange;
  131. expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
  132. focusChange = expectFocusChange();
  133. w.webContents.sendInputEvent(tabPressEvent);
  134. focusedElementId = await focusChange;
  135. expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
  136. focusChange = expectFocusChange();
  137. webviewContents.sendInputEvent(tabPressEvent);
  138. focusedElementId = await focusChange;
  139. expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
  140. focusChange = expectFocusChange();
  141. webviewContents.sendInputEvent(tabPressEvent);
  142. focusedElementId = await focusChange;
  143. expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`);
  144. focusChange = expectFocusChange();
  145. w.webContents.sendInputEvent(tabPressEvent);
  146. focusedElementId = await focusChange;
  147. expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`);
  148. });
  149. });
  150. describe('a SHIFT + TAB press', () => {
  151. const shiftTabPressEvent: any = {
  152. type: 'keyDown',
  153. modifiers: ['Shift'],
  154. keyCode: 'Tab'
  155. };
  156. it('moves focus to the previous focusable item', async () => {
  157. let focusChange = expectFocusChange();
  158. w.webContents.sendInputEvent(shiftTabPressEvent);
  159. let focusedElementId = await focusChange;
  160. expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`);
  161. focusChange = expectFocusChange();
  162. w.webContents.sendInputEvent(shiftTabPressEvent);
  163. focusedElementId = await focusChange;
  164. expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
  165. focusChange = expectFocusChange();
  166. webviewContents.sendInputEvent(shiftTabPressEvent);
  167. focusedElementId = await focusChange;
  168. expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
  169. focusChange = expectFocusChange();
  170. webviewContents.sendInputEvent(shiftTabPressEvent);
  171. focusedElementId = await focusChange;
  172. expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
  173. focusChange = expectFocusChange();
  174. w.webContents.sendInputEvent(shiftTabPressEvent);
  175. focusedElementId = await focusChange;
  176. expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`);
  177. focusChange = expectFocusChange();
  178. w.webContents.sendInputEvent(shiftTabPressEvent);
  179. focusedElementId = await focusChange;
  180. expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`);
  181. });
  182. });
  183. });
  184. describe('web security', () => {
  185. afterEach(closeAllWindows);
  186. let server: http.Server;
  187. let serverUrl: string;
  188. before(async () => {
  189. server = http.createServer((req, res) => {
  190. res.setHeader('Content-Type', 'text/html');
  191. res.end('<body>');
  192. });
  193. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  194. serverUrl = `http://localhost:${(server.address() as any).port}`;
  195. });
  196. after(() => {
  197. server.close();
  198. });
  199. it('engages CORB when web security is not disabled', async () => {
  200. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
  201. const p = emittedOnce(ipcMain, 'success');
  202. await w.loadURL(`data:text/html,<script>
  203. const s = document.createElement('script')
  204. s.src = "${serverUrl}"
  205. // The script will load successfully but its body will be emptied out
  206. // by CORB, so we don't expect a syntax error.
  207. s.onload = () => { require('electron').ipcRenderer.send('success') }
  208. document.documentElement.appendChild(s)
  209. </script>`);
  210. await p;
  211. });
  212. // TODO(codebytere): Re-enable after Chromium fixes upstream v8_scriptormodule_legacy_lifetime crash.
  213. xit('bypasses CORB when web security is disabled', async () => {
  214. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
  215. const p = emittedOnce(ipcMain, 'success');
  216. await w.loadURL(`data:text/html,
  217. <script>
  218. window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) }
  219. </script>
  220. <script src="${serverUrl}"></script>`);
  221. await p;
  222. });
  223. it('engages CORS when web security is not disabled', async () => {
  224. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
  225. const p = emittedOnce(ipcMain, 'response');
  226. await w.loadURL(`data:text/html,<script>
  227. (async function() {
  228. try {
  229. await fetch('${serverUrl}');
  230. require('electron').ipcRenderer.send('response', 'passed');
  231. } catch {
  232. require('electron').ipcRenderer.send('response', 'failed');
  233. }
  234. })();
  235. </script>`);
  236. const [, response] = await p;
  237. expect(response).to.equal('failed');
  238. });
  239. it('bypasses CORS when web security is disabled', async () => {
  240. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
  241. const p = emittedOnce(ipcMain, 'response');
  242. await w.loadURL(`data:text/html,<script>
  243. (async function() {
  244. try {
  245. await fetch('${serverUrl}');
  246. require('electron').ipcRenderer.send('response', 'passed');
  247. } catch {
  248. require('electron').ipcRenderer.send('response', 'failed');
  249. }
  250. })();
  251. </script>`);
  252. const [, response] = await p;
  253. expect(response).to.equal('passed');
  254. });
  255. describe('accessing file://', () => {
  256. async function loadFile (w: BrowserWindow) {
  257. const thisFile = url.format({
  258. pathname: __filename.replace(/\\/g, '/'),
  259. protocol: 'file',
  260. slashes: true
  261. });
  262. await w.loadURL(`data:text/html,<script>
  263. function loadFile() {
  264. return new Promise((resolve) => {
  265. fetch('${thisFile}').then(
  266. () => resolve('loaded'),
  267. () => resolve('failed')
  268. )
  269. });
  270. }
  271. </script>`);
  272. return await w.webContents.executeJavaScript('loadFile()');
  273. }
  274. it('is forbidden when web security is enabled', async () => {
  275. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } });
  276. const result = await loadFile(w);
  277. expect(result).to.equal('failed');
  278. });
  279. it('is allowed when web security is disabled', async () => {
  280. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } });
  281. const result = await loadFile(w);
  282. expect(result).to.equal('loaded');
  283. });
  284. });
  285. describe('wasm-eval csp', () => {
  286. async function loadWasm (csp: string) {
  287. const w = new BrowserWindow({
  288. show: false,
  289. webPreferences: {
  290. sandbox: true,
  291. enableBlinkFeatures: 'WebAssemblyCSP'
  292. }
  293. });
  294. await w.loadURL(`data:text/html,<head>
  295. <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}">
  296. </head>
  297. <script>
  298. function loadWasm() {
  299. const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
  300. return new Promise((resolve) => {
  301. WebAssembly.instantiate(wasmBin).then(() => {
  302. resolve('loaded')
  303. }).catch((error) => {
  304. resolve(error.message)
  305. })
  306. });
  307. }
  308. </script>`);
  309. return await w.webContents.executeJavaScript('loadWasm()');
  310. }
  311. it('wasm codegen is disallowed by default', async () => {
  312. const r = await loadWasm('');
  313. expect(r).to.equal('WebAssembly.instantiate(): Wasm code generation disallowed by embedder');
  314. });
  315. it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => {
  316. const r = await loadWasm("'wasm-unsafe-eval'");
  317. expect(r).to.equal('loaded');
  318. });
  319. });
  320. it('does not crash when multiple WebContent are created with web security disabled', () => {
  321. const options = { show: false, webPreferences: { webSecurity: false } };
  322. const w1 = new BrowserWindow(options);
  323. w1.loadURL(serverUrl);
  324. const w2 = new BrowserWindow(options);
  325. w2.loadURL(serverUrl);
  326. });
  327. });
  328. describe('command line switches', () => {
  329. let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
  330. afterEach(() => {
  331. if (appProcess && !appProcess.killed) {
  332. appProcess.kill();
  333. appProcess = undefined;
  334. }
  335. });
  336. describe('--lang switch', () => {
  337. const currentLocale = app.getLocale();
  338. const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
  339. const appPath = path.join(fixturesPath, 'api', 'locale-check');
  340. const args = [appPath, `--set-lang=${locale}`];
  341. if (printEnv) {
  342. args.push('--print-env');
  343. }
  344. appProcess = ChildProcess.spawn(process.execPath, args);
  345. let output = '';
  346. appProcess.stdout.on('data', (data) => { output += data; });
  347. let stderr = '';
  348. appProcess.stderr.on('data', (data) => { stderr += data; });
  349. const [code, signal] = await emittedOnce(appProcess, 'exit');
  350. if (code !== 0) {
  351. throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
  352. }
  353. output = output.replace(/(\r\n|\n|\r)/gm, '');
  354. expect(output).to.equal(result);
  355. };
  356. it('should set the locale', async () => testLocale('fr', 'fr'));
  357. it('should not set an invalid locale', async () => testLocale('asdfkl', currentLocale));
  358. const lcAll = String(process.env.LC_ALL);
  359. ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
  360. // The LC_ALL env should not be set to DOM locale string.
  361. expect(lcAll).to.not.equal(app.getLocale());
  362. });
  363. ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
  364. ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
  365. ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
  366. });
  367. describe('--remote-debugging-pipe switch', () => {
  368. it('should expose CDP via pipe', async () => {
  369. const electronPath = process.execPath;
  370. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
  371. stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
  372. }) as ChildProcess.ChildProcessWithoutNullStreams;
  373. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  374. const pipe = new PipeTransport(stdio[3], stdio[4]);
  375. const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
  376. pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
  377. const message = (await versionPromise) as any;
  378. expect(message.id).to.equal(1);
  379. expect(message.result.product).to.contain('Chrome');
  380. expect(message.result.userAgent).to.contain('Electron');
  381. });
  382. it('should override --remote-debugging-port switch', async () => {
  383. const electronPath = process.execPath;
  384. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], {
  385. stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe']
  386. }) as ChildProcess.ChildProcessWithoutNullStreams;
  387. let stderr = '';
  388. appProcess.stderr.on('data', (data: string) => { stderr += data; });
  389. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  390. const pipe = new PipeTransport(stdio[3], stdio[4]);
  391. const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
  392. pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
  393. const message = (await versionPromise) as any;
  394. expect(message.id).to.equal(1);
  395. expect(stderr).to.not.include('DevTools listening on');
  396. });
  397. it('should shut down Electron upon Browser.close CDP command', async () => {
  398. const electronPath = process.execPath;
  399. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
  400. stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
  401. }) as ChildProcess.ChildProcessWithoutNullStreams;
  402. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  403. const pipe = new PipeTransport(stdio[3], stdio[4]);
  404. pipe.send({ id: 1, method: 'Browser.close', params: {} });
  405. await new Promise(resolve => { appProcess!.on('exit', resolve); });
  406. });
  407. });
  408. describe('--remote-debugging-port switch', () => {
  409. it('should display the discovery page', (done) => {
  410. const electronPath = process.execPath;
  411. let output = '';
  412. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']);
  413. appProcess.stdout.on('data', (data) => {
  414. console.log(data);
  415. });
  416. appProcess.stderr.on('data', (data) => {
  417. console.log(data);
  418. output += data;
  419. const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
  420. if (m) {
  421. appProcess!.stderr.removeAllListeners('data');
  422. const port = m[1];
  423. http.get(`http://127.0.0.1:${port}`, (res) => {
  424. try {
  425. expect(res.statusCode).to.eql(200);
  426. expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
  427. done();
  428. } catch (e) {
  429. done(e);
  430. } finally {
  431. res.destroy();
  432. }
  433. });
  434. }
  435. });
  436. });
  437. });
  438. });
  439. describe('chromium features', () => {
  440. afterEach(closeAllWindows);
  441. describe('accessing key names also used as Node.js module names', () => {
  442. it('does not crash', (done) => {
  443. const w = new BrowserWindow({ show: false });
  444. w.webContents.once('did-finish-load', () => { done(); });
  445. w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
  446. w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
  447. });
  448. });
  449. describe('loading jquery', () => {
  450. it('does not crash', (done) => {
  451. const w = new BrowserWindow({ show: false });
  452. w.webContents.once('did-finish-load', () => { done(); });
  453. w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
  454. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
  455. });
  456. });
  457. describe('navigator.languages', () => {
  458. it('should return the system locale only', async () => {
  459. const appLocale = app.getLocale();
  460. const w = new BrowserWindow({ show: false });
  461. await w.loadURL('about:blank');
  462. const languages = await w.webContents.executeJavaScript('navigator.languages');
  463. expect(languages.length).to.be.greaterThan(0);
  464. expect(languages).to.contain(appLocale);
  465. });
  466. });
  467. describe('navigator.serviceWorker', () => {
  468. it('should register for file scheme', (done) => {
  469. const w = new BrowserWindow({
  470. show: false,
  471. webPreferences: {
  472. nodeIntegration: true,
  473. partition: 'sw-file-scheme-spec',
  474. contextIsolation: false
  475. }
  476. });
  477. w.webContents.on('ipc-message', (event, channel, message) => {
  478. if (channel === 'reload') {
  479. w.webContents.reload();
  480. } else if (channel === 'error') {
  481. done(message);
  482. } else if (channel === 'response') {
  483. expect(message).to.equal('Hello from serviceWorker!');
  484. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  485. storages: ['serviceworkers']
  486. }).then(() => done());
  487. }
  488. });
  489. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  490. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  491. });
  492. it('should register for intercepted file scheme', (done) => {
  493. const customSession = session.fromPartition('intercept-file');
  494. customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
  495. let file = url.parse(request.url).pathname!;
  496. if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
  497. const content = fs.readFileSync(path.normalize(file));
  498. const ext = path.extname(file);
  499. let type = 'text/html';
  500. if (ext === '.js') type = 'application/javascript';
  501. callback({ data: content, mimeType: type } as any);
  502. });
  503. const w = new BrowserWindow({
  504. show: false,
  505. webPreferences: {
  506. nodeIntegration: true,
  507. session: customSession,
  508. contextIsolation: false
  509. }
  510. });
  511. w.webContents.on('ipc-message', (event, channel, message) => {
  512. if (channel === 'reload') {
  513. w.webContents.reload();
  514. } else if (channel === 'error') {
  515. done(`unexpected error : ${message}`);
  516. } else if (channel === 'response') {
  517. expect(message).to.equal('Hello from serviceWorker!');
  518. customSession.clearStorageData({
  519. storages: ['serviceworkers']
  520. }).then(() => {
  521. customSession.protocol.uninterceptProtocol('file');
  522. done();
  523. });
  524. }
  525. });
  526. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  527. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  528. });
  529. it('should register for custom scheme', (done) => {
  530. const customSession = session.fromPartition('custom-scheme');
  531. customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => {
  532. let file = url.parse(request.url).pathname!;
  533. if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
  534. callback({ path: path.normalize(file) } as any);
  535. });
  536. const w = new BrowserWindow({
  537. show: false,
  538. webPreferences: {
  539. nodeIntegration: true,
  540. session: customSession,
  541. contextIsolation: false
  542. }
  543. });
  544. w.webContents.on('ipc-message', (event, channel, message) => {
  545. if (channel === 'reload') {
  546. w.webContents.reload();
  547. } else if (channel === 'error') {
  548. done(`unexpected error : ${message}`);
  549. } else if (channel === 'response') {
  550. expect(message).to.equal('Hello from serviceWorker!');
  551. customSession.clearStorageData({
  552. storages: ['serviceworkers']
  553. }).then(() => {
  554. customSession.protocol.uninterceptProtocol(serviceWorkerScheme);
  555. done();
  556. });
  557. }
  558. });
  559. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  560. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html'));
  561. });
  562. it('should not crash when nodeIntegration is enabled', (done) => {
  563. const w = new BrowserWindow({
  564. show: false,
  565. webPreferences: {
  566. nodeIntegration: true,
  567. nodeIntegrationInWorker: true,
  568. partition: 'sw-file-scheme-worker-spec',
  569. contextIsolation: false
  570. }
  571. });
  572. w.webContents.on('ipc-message', (event, channel, message) => {
  573. if (channel === 'reload') {
  574. w.webContents.reload();
  575. } else if (channel === 'error') {
  576. done(`unexpected error : ${message}`);
  577. } else if (channel === 'response') {
  578. expect(message).to.equal('Hello from serviceWorker!');
  579. session.fromPartition('sw-file-scheme-worker-spec').clearStorageData({
  580. storages: ['serviceworkers']
  581. }).then(() => done());
  582. }
  583. });
  584. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  585. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  586. });
  587. });
  588. describe('navigator.geolocation', () => {
  589. before(function () {
  590. if (!features.isFakeLocationProviderEnabled()) {
  591. return this.skip();
  592. }
  593. });
  594. it('returns error when permission is denied', async () => {
  595. const w = new BrowserWindow({
  596. show: false,
  597. webPreferences: {
  598. nodeIntegration: true,
  599. partition: 'geolocation-spec',
  600. contextIsolation: false
  601. }
  602. });
  603. const message = emittedOnce(w.webContents, 'ipc-message');
  604. w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
  605. if (permission === 'geolocation') {
  606. callback(false);
  607. } else {
  608. callback(true);
  609. }
  610. });
  611. w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
  612. const [, channel] = await message;
  613. expect(channel).to.equal('success', 'unexpected response from geolocation api');
  614. });
  615. });
  616. describe('web workers', () => {
  617. let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
  618. afterEach(() => {
  619. if (appProcess && !appProcess.killed) {
  620. appProcess.kill();
  621. appProcess = undefined;
  622. }
  623. });
  624. it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => {
  625. const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths');
  626. appProcess = ChildProcess.spawn(process.execPath, [appPath]);
  627. const [code] = await emittedOnce(appProcess, 'exit');
  628. expect(code).to.equal(0);
  629. });
  630. });
  631. describe('form submit', () => {
  632. let server: http.Server;
  633. let serverUrl: string;
  634. before(async () => {
  635. server = http.createServer((req, res) => {
  636. let body = '';
  637. req.on('data', (chunk) => {
  638. body += chunk;
  639. });
  640. res.setHeader('Content-Type', 'application/json');
  641. req.on('end', () => {
  642. res.end(`body:${body}`);
  643. });
  644. });
  645. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  646. serverUrl = `http://localhost:${(server.address() as any).port}`;
  647. });
  648. after(async () => {
  649. server.close();
  650. await closeAllWindows();
  651. });
  652. [true, false].forEach((isSandboxEnabled) =>
  653. describe(`sandbox=${isSandboxEnabled}`, () => {
  654. it('posts data in the same window', async () => {
  655. const w = new BrowserWindow({
  656. show: false,
  657. webPreferences: {
  658. sandbox: isSandboxEnabled
  659. }
  660. });
  661. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  662. const loadPromise = emittedOnce(w.webContents, 'did-finish-load');
  663. w.webContents.executeJavaScript(`
  664. const form = document.querySelector('form')
  665. form.action = '${serverUrl}';
  666. form.submit();
  667. `);
  668. await loadPromise;
  669. const res = await w.webContents.executeJavaScript('document.body.innerText');
  670. expect(res).to.equal('body:greeting=hello');
  671. });
  672. it('posts data to a new window with target=_blank', async () => {
  673. const w = new BrowserWindow({
  674. show: false,
  675. webPreferences: {
  676. sandbox: isSandboxEnabled
  677. }
  678. });
  679. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  680. const windowCreatedPromise = emittedOnce(app, 'browser-window-created');
  681. w.webContents.executeJavaScript(`
  682. const form = document.querySelector('form')
  683. form.action = '${serverUrl}';
  684. form.target = '_blank';
  685. form.submit();
  686. `);
  687. const [, newWin] = await windowCreatedPromise;
  688. const res = await newWin.webContents.executeJavaScript('document.body.innerText');
  689. expect(res).to.equal('body:greeting=hello');
  690. });
  691. })
  692. );
  693. });
  694. describe('window.open', () => {
  695. for (const show of [true, false]) {
  696. it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => {
  697. const w = new BrowserWindow({ show });
  698. // toggle visibility
  699. if (show) {
  700. w.hide();
  701. } else {
  702. w.show();
  703. }
  704. defer(() => { w.close(); });
  705. const newWindow = emittedOnce(w.webContents, 'new-window');
  706. w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
  707. const [,,,, options] = await newWindow;
  708. expect(options.show).to.equal(true);
  709. });
  710. }
  711. it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
  712. // NB. webSecurity is disabled because native window.open() is not
  713. // allowed to load devtools:// URLs.
  714. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } });
  715. w.loadURL('about:blank');
  716. w.webContents.executeJavaScript(`
  717. { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null }
  718. `);
  719. const [, contents] = await emittedOnce(app, 'web-contents-created');
  720. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  721. expect(typeofProcessGlobal).to.equal('undefined');
  722. });
  723. it('can disable node integration when it is enabled on the parent window', async () => {
  724. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  725. w.loadURL('about:blank');
  726. w.webContents.executeJavaScript(`
  727. { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null }
  728. `);
  729. const [, contents] = await emittedOnce(app, 'web-contents-created');
  730. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  731. expect(typeofProcessGlobal).to.equal('undefined');
  732. });
  733. // TODO(jkleinsc) fix this flaky test on WOA
  734. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => {
  735. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } });
  736. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  737. const windowUrl = require('url').format({
  738. pathname: `${fixturesPath}/pages/window-no-javascript.html`,
  739. protocol: 'file',
  740. slashes: true
  741. });
  742. w.webContents.executeJavaScript(`
  743. { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null }
  744. `);
  745. const [, contents] = await emittedOnce(app, 'web-contents-created');
  746. await emittedOnce(contents, 'did-finish-load');
  747. // Click link on page
  748. contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
  749. contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
  750. const [, window] = await emittedOnce(app, 'browser-window-created');
  751. const preferences = window.webContents.getLastWebPreferences();
  752. expect(preferences.javascript).to.be.false();
  753. });
  754. it('defines a window.location getter', async () => {
  755. let targetURL: string;
  756. if (process.platform === 'win32') {
  757. targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
  758. } else {
  759. targetURL = `file://${fixturesPath}/pages/base-page.html`;
  760. }
  761. const w = new BrowserWindow({ show: false });
  762. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  763. w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
  764. const [, window] = await emittedOnce(app, 'browser-window-created');
  765. await emittedOnce(window.webContents, 'did-finish-load');
  766. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
  767. });
  768. it('defines a window.location setter', async () => {
  769. const w = new BrowserWindow({ show: false });
  770. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  771. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  772. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  773. await emittedOnce(webContents, 'did-finish-load');
  774. // When it loads, redirect
  775. w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  776. await emittedOnce(webContents, 'did-finish-load');
  777. });
  778. it('defines a window.location.href setter', async () => {
  779. const w = new BrowserWindow({ show: false });
  780. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  781. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  782. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  783. await emittedOnce(webContents, 'did-finish-load');
  784. // When it loads, redirect
  785. w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  786. await emittedOnce(webContents, 'did-finish-load');
  787. });
  788. it('open a blank page when no URL is specified', async () => {
  789. const w = new BrowserWindow({ show: false });
  790. w.loadURL('about:blank');
  791. w.webContents.executeJavaScript('{ b = window.open(); null }');
  792. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  793. await emittedOnce(webContents, 'did-finish-load');
  794. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  795. });
  796. it('open a blank page when an empty URL is specified', async () => {
  797. const w = new BrowserWindow({ show: false });
  798. w.loadURL('about:blank');
  799. w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
  800. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  801. await emittedOnce(webContents, 'did-finish-load');
  802. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  803. });
  804. it('does not throw an exception when the frameName is a built-in object property', async () => {
  805. const w = new BrowserWindow({ show: false });
  806. w.loadURL('about:blank');
  807. w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
  808. const [, , frameName] = await emittedOnce(w.webContents, 'new-window');
  809. expect(frameName).to.equal('__proto__');
  810. });
  811. });
  812. describe('window.opener', () => {
  813. it('is null for main window', async () => {
  814. const w = new BrowserWindow({
  815. show: false,
  816. webPreferences: {
  817. nodeIntegration: true,
  818. contextIsolation: false
  819. }
  820. });
  821. w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
  822. const [, channel, opener] = await emittedOnce(w.webContents, 'ipc-message');
  823. expect(channel).to.equal('opener');
  824. expect(opener).to.equal(null);
  825. });
  826. });
  827. describe('navigator.mediaDevices', () => {
  828. afterEach(closeAllWindows);
  829. afterEach(() => {
  830. session.defaultSession.setPermissionCheckHandler(null);
  831. session.defaultSession.setPermissionRequestHandler(null);
  832. });
  833. it('can return labels of enumerated devices', async () => {
  834. const w = new BrowserWindow({ show: false });
  835. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  836. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  837. expect(labels.some((l: any) => l)).to.be.true();
  838. });
  839. it('does not return labels of enumerated devices when permission denied', async () => {
  840. session.defaultSession.setPermissionCheckHandler(() => false);
  841. const w = new BrowserWindow({ show: false });
  842. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  843. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  844. expect(labels.some((l: any) => l)).to.be.false();
  845. });
  846. it('returns the same device ids across reloads', async () => {
  847. const ses = session.fromPartition('persist:media-device-id');
  848. const w = new BrowserWindow({
  849. show: false,
  850. webPreferences: {
  851. nodeIntegration: true,
  852. session: ses,
  853. contextIsolation: false
  854. }
  855. });
  856. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  857. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  858. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  859. expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
  860. });
  861. it('can return new device id when cookie storage is cleared', async () => {
  862. const ses = session.fromPartition('persist:media-device-id');
  863. const w = new BrowserWindow({
  864. show: false,
  865. webPreferences: {
  866. nodeIntegration: true,
  867. session: ses,
  868. contextIsolation: false
  869. }
  870. });
  871. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  872. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  873. await ses.clearStorageData({ storages: ['cookies'] });
  874. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  875. expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
  876. });
  877. it('provides a securityOrigin to the request handler', async () => {
  878. session.defaultSession.setPermissionRequestHandler(
  879. (wc, permission, callback, details) => {
  880. if (details.securityOrigin !== undefined) {
  881. callback(true);
  882. } else {
  883. callback(false);
  884. }
  885. }
  886. );
  887. const w = new BrowserWindow({ show: false });
  888. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  889. const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({
  890. video: {
  891. mandatory: {
  892. chromeMediaSource: "desktop",
  893. minWidth: 1280,
  894. maxWidth: 1280,
  895. minHeight: 720,
  896. maxHeight: 720
  897. }
  898. }
  899. }).then((stream) => stream.getVideoTracks())`);
  900. expect(labels.some((l: any) => l)).to.be.true();
  901. });
  902. });
  903. describe('window.opener access', () => {
  904. const scheme = 'app';
  905. const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
  906. const httpUrl1 = `${scheme}://origin1`;
  907. const httpUrl2 = `${scheme}://origin2`;
  908. const fileBlank = `file://${fixturesPath}/pages/blank.html`;
  909. const httpBlank = `${scheme}://origin1/blank`;
  910. const table = [
  911. { parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false },
  912. { parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false },
  913. // {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open()
  914. // {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open()
  915. // NB. this is different from Chrome's behavior, which isolates file: urls from each other
  916. { parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true },
  917. { parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true },
  918. { parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true },
  919. { parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true },
  920. { parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false },
  921. { parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false }
  922. ];
  923. const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
  924. before(() => {
  925. protocol.registerFileProtocol(scheme, (request, callback) => {
  926. if (request.url.includes('blank')) {
  927. callback(`${fixturesPath}/pages/blank.html`);
  928. } else {
  929. callback(`${fixturesPath}/pages/window-opener-location.html`);
  930. }
  931. });
  932. });
  933. after(() => {
  934. protocol.unregisterProtocol(scheme);
  935. });
  936. afterEach(closeAllWindows);
  937. describe('when opened from main window', () => {
  938. for (const { parent, child, nodeIntegration, openerAccessible } of table) {
  939. for (const sandboxPopup of [false, true]) {
  940. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  941. it(description, async () => {
  942. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  943. w.webContents.setWindowOpenHandler(() => ({
  944. action: 'allow',
  945. overrideBrowserWindowOptions: {
  946. webPreferences: {
  947. sandbox: sandboxPopup
  948. }
  949. }
  950. }));
  951. await w.loadURL(parent);
  952. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
  953. window.addEventListener('message', function f(e) {
  954. resolve(e.data)
  955. })
  956. window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
  957. })`);
  958. if (openerAccessible) {
  959. expect(childOpenerLocation).to.be.a('string');
  960. } else {
  961. expect(childOpenerLocation).to.be.null();
  962. }
  963. });
  964. }
  965. }
  966. });
  967. describe('when opened from <webview>', () => {
  968. for (const { parent, child, nodeIntegration, openerAccessible } of table) {
  969. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  970. it(description, async () => {
  971. // This test involves three contexts:
  972. // 1. The root BrowserWindow in which the test is run,
  973. // 2. A <webview> belonging to the root window,
  974. // 3. A window opened by calling window.open() from within the <webview>.
  975. // We are testing whether context (3) can access context (2) under various conditions.
  976. // This is context (1), the base window for the test.
  977. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
  978. await w.loadURL('about:blank');
  979. const parentCode = `new Promise((resolve) => {
  980. // This is context (3), a child window of the WebView.
  981. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes")
  982. window.addEventListener("message", e => {
  983. resolve(e.data)
  984. })
  985. })`;
  986. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  987. // This is context (2), a WebView which will call window.open()
  988. const webview = new WebView()
  989. webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
  990. webview.setAttribute('webpreferences', 'contextIsolation=no')
  991. webview.setAttribute('allowpopups', 'on')
  992. webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
  993. webview.addEventListener('dom-ready', async () => {
  994. webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
  995. })
  996. document.body.appendChild(webview)
  997. })`);
  998. if (openerAccessible) {
  999. expect(childOpenerLocation).to.be.a('string');
  1000. } else {
  1001. expect(childOpenerLocation).to.be.null();
  1002. }
  1003. });
  1004. }
  1005. });
  1006. });
  1007. describe('storage', () => {
  1008. describe('custom non standard schemes', () => {
  1009. const protocolName = 'storage';
  1010. let contents: WebContents;
  1011. before(() => {
  1012. protocol.registerFileProtocol(protocolName, (request, callback) => {
  1013. const parsedUrl = url.parse(request.url);
  1014. let filename;
  1015. switch (parsedUrl.pathname) {
  1016. case '/localStorage' : filename = 'local_storage.html'; break;
  1017. case '/sessionStorage' : filename = 'session_storage.html'; break;
  1018. case '/WebSQL' : filename = 'web_sql.html'; break;
  1019. case '/indexedDB' : filename = 'indexed_db.html'; break;
  1020. case '/cookie' : filename = 'cookie.html'; break;
  1021. default : filename = '';
  1022. }
  1023. callback({ path: `${fixturesPath}/pages/storage/${filename}` });
  1024. });
  1025. });
  1026. after(() => {
  1027. protocol.unregisterProtocol(protocolName);
  1028. });
  1029. beforeEach(() => {
  1030. contents = (webContents as any).create({
  1031. nodeIntegration: true,
  1032. contextIsolation: false
  1033. });
  1034. });
  1035. afterEach(() => {
  1036. (contents as any).destroy();
  1037. contents = null as any;
  1038. });
  1039. it('cannot access localStorage', async () => {
  1040. const response = emittedOnce(ipcMain, 'local-storage-response');
  1041. contents.loadURL(protocolName + '://host/localStorage');
  1042. const [, error] = await response;
  1043. expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.');
  1044. });
  1045. it('cannot access sessionStorage', async () => {
  1046. const response = emittedOnce(ipcMain, 'session-storage-response');
  1047. contents.loadURL(`${protocolName}://host/sessionStorage`);
  1048. const [, error] = await response;
  1049. expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.');
  1050. });
  1051. it('cannot access WebSQL database', async () => {
  1052. const response = emittedOnce(ipcMain, 'web-sql-response');
  1053. contents.loadURL(`${protocolName}://host/WebSQL`);
  1054. const [, error] = await response;
  1055. expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.');
  1056. });
  1057. it('cannot access indexedDB', async () => {
  1058. const response = emittedOnce(ipcMain, 'indexed-db-response');
  1059. contents.loadURL(`${protocolName}://host/indexedDB`);
  1060. const [, error] = await response;
  1061. expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.');
  1062. });
  1063. it('cannot access cookie', async () => {
  1064. const response = emittedOnce(ipcMain, 'cookie-response');
  1065. contents.loadURL(`${protocolName}://host/cookie`);
  1066. const [, error] = await response;
  1067. expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.');
  1068. });
  1069. });
  1070. describe('can be accessed', () => {
  1071. let server: http.Server;
  1072. let serverUrl: string;
  1073. let serverCrossSiteUrl: string;
  1074. before((done) => {
  1075. server = http.createServer((req, res) => {
  1076. const respond = () => {
  1077. if (req.url === '/redirect-cross-site') {
  1078. res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
  1079. res.statusCode = 302;
  1080. res.end();
  1081. } else if (req.url === '/redirected') {
  1082. res.end('<html><script>window.localStorage</script></html>');
  1083. } else {
  1084. res.end();
  1085. }
  1086. };
  1087. setTimeout(respond, 0);
  1088. });
  1089. server.listen(0, '127.0.0.1', () => {
  1090. serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  1091. serverCrossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`;
  1092. done();
  1093. });
  1094. });
  1095. after(() => {
  1096. server.close();
  1097. server = null as any;
  1098. });
  1099. afterEach(closeAllWindows);
  1100. const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
  1101. it(testTitle, async () => {
  1102. const w = new BrowserWindow({
  1103. show: false,
  1104. ...extraPreferences
  1105. });
  1106. let redirected = false;
  1107. w.webContents.on('crashed', () => {
  1108. expect.fail('renderer crashed / was killed');
  1109. });
  1110. w.webContents.on('did-redirect-navigation', (event, url) => {
  1111. expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
  1112. redirected = true;
  1113. });
  1114. await w.loadURL(`${serverUrl}/redirect-cross-site`);
  1115. expect(redirected).to.be.true('didnt redirect');
  1116. });
  1117. };
  1118. testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
  1119. testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
  1120. });
  1121. describe('enableWebSQL webpreference', () => {
  1122. const origin = `${standardScheme}://fake-host`;
  1123. const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
  1124. const sqlPartition = 'web-sql-preference-test';
  1125. const sqlSession = session.fromPartition(sqlPartition);
  1126. const securityError = 'An attempt was made to break through the security policy of the user agent.';
  1127. let contents: WebContents, w: BrowserWindow;
  1128. before(() => {
  1129. sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
  1130. callback({ path: filePath });
  1131. });
  1132. });
  1133. after(() => {
  1134. sqlSession.protocol.unregisterProtocol(standardScheme);
  1135. });
  1136. afterEach(async () => {
  1137. if (contents) {
  1138. (contents as any).destroy();
  1139. contents = null as any;
  1140. }
  1141. await closeAllWindows();
  1142. (w as any) = null;
  1143. });
  1144. it('default value allows websql', async () => {
  1145. contents = (webContents as any).create({
  1146. session: sqlSession,
  1147. nodeIntegration: true,
  1148. contextIsolation: false
  1149. });
  1150. contents.loadURL(origin);
  1151. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1152. expect(error).to.be.null();
  1153. });
  1154. it('when set to false can disallow websql', async () => {
  1155. contents = (webContents as any).create({
  1156. session: sqlSession,
  1157. nodeIntegration: true,
  1158. enableWebSQL: false,
  1159. contextIsolation: false
  1160. });
  1161. contents.loadURL(origin);
  1162. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1163. expect(error).to.equal(securityError);
  1164. });
  1165. it('when set to false does not disable indexedDB', async () => {
  1166. contents = (webContents as any).create({
  1167. session: sqlSession,
  1168. nodeIntegration: true,
  1169. enableWebSQL: false,
  1170. contextIsolation: false
  1171. });
  1172. contents.loadURL(origin);
  1173. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1174. expect(error).to.equal(securityError);
  1175. const dbName = 'random';
  1176. const result = await contents.executeJavaScript(`
  1177. new Promise((resolve, reject) => {
  1178. try {
  1179. let req = window.indexedDB.open('${dbName}');
  1180. req.onsuccess = (event) => {
  1181. let db = req.result;
  1182. resolve(db.name);
  1183. }
  1184. req.onerror = (event) => { resolve(event.target.code); }
  1185. } catch (e) {
  1186. resolve(e.message);
  1187. }
  1188. });
  1189. `);
  1190. expect(result).to.equal(dbName);
  1191. });
  1192. it('child webContents can override when the embedder has allowed websql', async () => {
  1193. w = new BrowserWindow({
  1194. show: false,
  1195. webPreferences: {
  1196. nodeIntegration: true,
  1197. webviewTag: true,
  1198. session: sqlSession,
  1199. contextIsolation: false
  1200. }
  1201. });
  1202. w.webContents.loadURL(origin);
  1203. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1204. expect(error).to.be.null();
  1205. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1206. await w.webContents.executeJavaScript(`
  1207. new Promise((resolve, reject) => {
  1208. const webview = new WebView();
  1209. webview.setAttribute('src', '${origin}');
  1210. webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no');
  1211. webview.setAttribute('partition', '${sqlPartition}');
  1212. webview.setAttribute('nodeIntegration', 'on');
  1213. document.body.appendChild(webview);
  1214. webview.addEventListener('dom-ready', () => resolve());
  1215. });
  1216. `);
  1217. const [, childError] = await webviewResult;
  1218. expect(childError).to.equal(securityError);
  1219. });
  1220. it('child webContents cannot override when the embedder has disallowed websql', async () => {
  1221. w = new BrowserWindow({
  1222. show: false,
  1223. webPreferences: {
  1224. nodeIntegration: true,
  1225. enableWebSQL: false,
  1226. webviewTag: true,
  1227. session: sqlSession,
  1228. contextIsolation: false
  1229. }
  1230. });
  1231. w.webContents.loadURL('data:text/html,<html></html>');
  1232. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1233. await w.webContents.executeJavaScript(`
  1234. new Promise((resolve, reject) => {
  1235. const webview = new WebView();
  1236. webview.setAttribute('src', '${origin}');
  1237. webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
  1238. webview.setAttribute('partition', '${sqlPartition}');
  1239. webview.setAttribute('nodeIntegration', 'on');
  1240. document.body.appendChild(webview);
  1241. webview.addEventListener('dom-ready', () => resolve());
  1242. });
  1243. `);
  1244. const [, childError] = await webviewResult;
  1245. expect(childError).to.equal(securityError);
  1246. });
  1247. it('child webContents can use websql when the embedder has allowed websql', async () => {
  1248. w = new BrowserWindow({
  1249. show: false,
  1250. webPreferences: {
  1251. nodeIntegration: true,
  1252. webviewTag: true,
  1253. session: sqlSession,
  1254. contextIsolation: false
  1255. }
  1256. });
  1257. w.webContents.loadURL(origin);
  1258. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1259. expect(error).to.be.null();
  1260. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1261. await w.webContents.executeJavaScript(`
  1262. new Promise((resolve, reject) => {
  1263. const webview = new WebView();
  1264. webview.setAttribute('src', '${origin}');
  1265. webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
  1266. webview.setAttribute('partition', '${sqlPartition}');
  1267. webview.setAttribute('nodeIntegration', 'on');
  1268. document.body.appendChild(webview);
  1269. webview.addEventListener('dom-ready', () => resolve());
  1270. });
  1271. `);
  1272. const [, childError] = await webviewResult;
  1273. expect(childError).to.be.null();
  1274. });
  1275. });
  1276. });
  1277. ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
  1278. const pdfSource = url.format({
  1279. pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'),
  1280. protocol: 'file',
  1281. slashes: true
  1282. });
  1283. it('successfully loads a PDF file', async () => {
  1284. const w = new BrowserWindow({ show: false });
  1285. w.loadURL(pdfSource);
  1286. await emittedOnce(w.webContents, 'did-finish-load');
  1287. });
  1288. it('opens when loading a pdf resource as top level navigation', async () => {
  1289. const w = new BrowserWindow({ show: false });
  1290. w.loadURL(pdfSource);
  1291. const [, contents] = await emittedOnce(app, 'web-contents-created');
  1292. await emittedOnce(contents, 'did-navigate');
  1293. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1294. });
  1295. it('opens when loading a pdf resource in a iframe', async () => {
  1296. const w = new BrowserWindow({ show: false });
  1297. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
  1298. const [, contents] = await emittedOnce(app, 'web-contents-created');
  1299. await emittedOnce(contents, 'did-navigate');
  1300. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1301. });
  1302. });
  1303. describe('window.history', () => {
  1304. describe('window.history.pushState', () => {
  1305. it('should push state after calling history.pushState() from the same url', async () => {
  1306. const w = new BrowserWindow({ show: false });
  1307. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1308. // History should have current page by now.
  1309. expect((w.webContents as any).length()).to.equal(1);
  1310. const waitCommit = emittedOnce(w.webContents, 'navigation-entry-committed');
  1311. w.webContents.executeJavaScript('window.history.pushState({}, "")');
  1312. await waitCommit;
  1313. // Initial page + pushed state.
  1314. expect((w.webContents as any).length()).to.equal(2);
  1315. });
  1316. });
  1317. });
  1318. describe('chrome://media-internals', () => {
  1319. it('loads the page successfully', async () => {
  1320. const w = new BrowserWindow({ show: false });
  1321. w.loadURL('chrome://media-internals');
  1322. const pageExists = await w.webContents.executeJavaScript(
  1323. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1324. );
  1325. expect(pageExists).to.be.true();
  1326. });
  1327. });
  1328. describe('chrome://webrtc-internals', () => {
  1329. it('loads the page successfully', async () => {
  1330. const w = new BrowserWindow({ show: false });
  1331. w.loadURL('chrome://webrtc-internals');
  1332. const pageExists = await w.webContents.executeJavaScript(
  1333. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1334. );
  1335. expect(pageExists).to.be.true();
  1336. });
  1337. });
  1338. describe('document.hasFocus', () => {
  1339. it('has correct value when multiple windows are opened', async () => {
  1340. const w1 = new BrowserWindow({ show: true });
  1341. const w2 = new BrowserWindow({ show: true });
  1342. const w3 = new BrowserWindow({ show: false });
  1343. await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1344. await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1345. await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1346. expect(webContents.getFocusedWebContents().id).to.equal(w2.webContents.id);
  1347. let focus = false;
  1348. focus = await w1.webContents.executeJavaScript(
  1349. 'document.hasFocus()'
  1350. );
  1351. expect(focus).to.be.false();
  1352. focus = await w2.webContents.executeJavaScript(
  1353. 'document.hasFocus()'
  1354. );
  1355. expect(focus).to.be.true();
  1356. focus = await w3.webContents.executeJavaScript(
  1357. 'document.hasFocus()'
  1358. );
  1359. expect(focus).to.be.false();
  1360. });
  1361. });
  1362. describe('navigator.userAgentData', () => {
  1363. // These tests are done on an http server because navigator.userAgentData
  1364. // requires a secure context.
  1365. let server: http.Server;
  1366. let serverUrl: string;
  1367. before(async () => {
  1368. server = http.createServer((req, res) => {
  1369. res.setHeader('Content-Type', 'text/html');
  1370. res.end('');
  1371. });
  1372. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1373. serverUrl = `http://localhost:${(server.address() as any).port}`;
  1374. });
  1375. after(() => {
  1376. server.close();
  1377. });
  1378. describe('is not empty', () => {
  1379. it('by default', async () => {
  1380. const w = new BrowserWindow({ show: false });
  1381. await w.loadURL(serverUrl);
  1382. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1383. expect(platform).not.to.be.empty();
  1384. });
  1385. it('when there is a session-wide UA override', async () => {
  1386. const ses = session.fromPartition(`${Math.random()}`);
  1387. ses.setUserAgent('foobar');
  1388. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  1389. await w.loadURL(serverUrl);
  1390. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1391. expect(platform).not.to.be.empty();
  1392. });
  1393. it('when there is a WebContents-specific UA override', async () => {
  1394. const w = new BrowserWindow({ show: false });
  1395. w.webContents.setUserAgent('foo');
  1396. await w.loadURL(serverUrl);
  1397. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1398. expect(platform).not.to.be.empty();
  1399. });
  1400. it('when there is a WebContents-specific UA override at load time', async () => {
  1401. const w = new BrowserWindow({ show: false });
  1402. await w.loadURL(serverUrl, {
  1403. userAgent: 'foo'
  1404. });
  1405. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1406. expect(platform).not.to.be.empty();
  1407. });
  1408. });
  1409. describe('brand list', () => {
  1410. it('contains chromium', async () => {
  1411. const w = new BrowserWindow({ show: false });
  1412. await w.loadURL(serverUrl);
  1413. const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands');
  1414. expect(brands.map((b: any) => b.brand)).to.include('Chromium');
  1415. });
  1416. });
  1417. });
  1418. });
  1419. describe('font fallback', () => {
  1420. async function getRenderedFonts (html: string) {
  1421. const w = new BrowserWindow({ show: false });
  1422. try {
  1423. await w.loadURL(`data:text/html,${html}`);
  1424. w.webContents.debugger.attach();
  1425. const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
  1426. const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
  1427. await sendCommand('CSS.enable');
  1428. const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
  1429. return fonts;
  1430. } finally {
  1431. w.close();
  1432. }
  1433. }
  1434. it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
  1435. const html = '<body style="font-family: sans-serif">test</body>';
  1436. const fonts = await getRenderedFonts(html);
  1437. expect(fonts).to.be.an('array');
  1438. expect(fonts).to.have.length(1);
  1439. if (process.platform === 'win32') {
  1440. expect(fonts[0].familyName).to.equal('Arial');
  1441. } else if (process.platform === 'darwin') {
  1442. expect(fonts[0].familyName).to.equal('Helvetica');
  1443. } else if (process.platform === 'linux') {
  1444. expect(fonts[0].familyName).to.equal('DejaVu Sans');
  1445. } // I think this depends on the distro? We don't specify a default.
  1446. });
  1447. ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
  1448. const html = `
  1449. <html lang="ja-JP">
  1450. <head>
  1451. <meta charset="utf-8" />
  1452. </head>
  1453. <body style="font-family: sans-serif">test 智史</body>
  1454. </html>
  1455. `;
  1456. const fonts = await getRenderedFonts(html);
  1457. expect(fonts).to.be.an('array');
  1458. expect(fonts).to.have.length(1);
  1459. 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'); }
  1460. });
  1461. });
  1462. describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
  1463. const fullscreenChildHtml = promisify(fs.readFile)(
  1464. path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
  1465. );
  1466. let w: BrowserWindow, server: http.Server;
  1467. before(() => {
  1468. server = http.createServer(async (_req, res) => {
  1469. res.writeHead(200, { 'Content-Type': 'text/html' });
  1470. res.write(await fullscreenChildHtml);
  1471. res.end();
  1472. });
  1473. server.listen(8989, '127.0.0.1');
  1474. });
  1475. beforeEach(() => {
  1476. w = new BrowserWindow({
  1477. show: true,
  1478. fullscreen: true,
  1479. webPreferences: {
  1480. nodeIntegration: true,
  1481. nodeIntegrationInSubFrames: true,
  1482. contextIsolation: false
  1483. }
  1484. });
  1485. });
  1486. afterEach(async () => {
  1487. await closeAllWindows();
  1488. (w as any) = null;
  1489. server.close();
  1490. });
  1491. it('can fullscreen from out-of-process iframes (OOPIFs)', async () => {
  1492. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  1493. const html =
  1494. '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>';
  1495. w.loadURL(`data:text/html,${html}`);
  1496. await fullscreenChange;
  1497. const fullscreenWidth = await w.webContents.executeJavaScript(
  1498. "document.querySelector('iframe').offsetWidth"
  1499. );
  1500. expect(fullscreenWidth > 0).to.be.true();
  1501. await w.webContents.executeJavaScript(
  1502. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  1503. );
  1504. await delay(500);
  1505. const width = await w.webContents.executeJavaScript(
  1506. "document.querySelector('iframe').offsetWidth"
  1507. );
  1508. expect(width).to.equal(0);
  1509. });
  1510. // TODO(jkleinsc) fix this flaky test on WOA
  1511. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => {
  1512. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  1513. w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
  1514. await fullscreenChange;
  1515. const fullscreenWidth = await w.webContents.executeJavaScript(
  1516. "document.querySelector('iframe').offsetWidth"
  1517. );
  1518. expect(fullscreenWidth > 0).to.true();
  1519. await w.webContents.executeJavaScript('document.exitFullscreen()');
  1520. const width = await w.webContents.executeJavaScript(
  1521. "document.querySelector('iframe').offsetWidth"
  1522. );
  1523. expect(width).to.equal(0);
  1524. });
  1525. });
  1526. describe('navigator.serial', () => {
  1527. let w: BrowserWindow;
  1528. before(async () => {
  1529. w = new BrowserWindow({
  1530. show: false
  1531. });
  1532. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1533. });
  1534. const getPorts: any = () => {
  1535. return w.webContents.executeJavaScript(`
  1536. navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
  1537. `, true);
  1538. };
  1539. after(closeAllWindows);
  1540. afterEach(() => {
  1541. session.defaultSession.setPermissionCheckHandler(null);
  1542. session.defaultSession.removeAllListeners('select-serial-port');
  1543. });
  1544. it('does not return a port if select-serial-port event is not defined', async () => {
  1545. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1546. const port = await getPorts();
  1547. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1548. });
  1549. it('does not return a port when permission denied', async () => {
  1550. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1551. callback(portList[0].portId);
  1552. });
  1553. session.defaultSession.setPermissionCheckHandler(() => false);
  1554. const port = await getPorts();
  1555. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1556. });
  1557. it('does not crash when select-serial-port is called with an invalid port', async () => {
  1558. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1559. callback('i-do-not-exist');
  1560. });
  1561. const port = await getPorts();
  1562. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1563. });
  1564. it('returns a port when select-serial-port event is defined', async () => {
  1565. let havePorts = false;
  1566. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1567. if (portList.length > 0) {
  1568. havePorts = true;
  1569. callback(portList[0].portId);
  1570. } else {
  1571. callback('');
  1572. }
  1573. });
  1574. const port = await getPorts();
  1575. if (havePorts) {
  1576. expect(port).to.equal('[object SerialPort]');
  1577. } else {
  1578. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1579. }
  1580. });
  1581. it('navigator.serial.getPorts() returns values', async () => {
  1582. let havePorts = false;
  1583. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1584. if (portList.length > 0) {
  1585. havePorts = true;
  1586. callback(portList[0].portId);
  1587. } else {
  1588. callback('');
  1589. }
  1590. });
  1591. await getPorts();
  1592. if (havePorts) {
  1593. const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
  1594. expect(grantedPorts).to.not.be.empty();
  1595. }
  1596. });
  1597. });
  1598. describe('navigator.clipboard', () => {
  1599. let w: BrowserWindow;
  1600. before(async () => {
  1601. w = new BrowserWindow({
  1602. webPreferences: {
  1603. enableBlinkFeatures: 'Serial'
  1604. }
  1605. });
  1606. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1607. });
  1608. const readClipboard: any = () => {
  1609. return w.webContents.executeJavaScript(`
  1610. navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
  1611. `, true);
  1612. };
  1613. after(closeAllWindows);
  1614. afterEach(() => {
  1615. session.defaultSession.setPermissionRequestHandler(null);
  1616. });
  1617. it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
  1618. const clipboard = await readClipboard();
  1619. expect(clipboard).to.not.equal('Read permission denied.');
  1620. });
  1621. it('returns an error when permission denied', async () => {
  1622. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  1623. if (permission === 'clipboard-read') {
  1624. callback(false);
  1625. } else {
  1626. callback(true);
  1627. }
  1628. });
  1629. const clipboard = await readClipboard();
  1630. expect(clipboard).to.equal('Read permission denied.');
  1631. });
  1632. it('returns clipboard contents when permission is granted', async () => {
  1633. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  1634. if (permission === 'clipboard-read') {
  1635. callback(true);
  1636. } else {
  1637. callback(false);
  1638. }
  1639. });
  1640. const clipboard = await readClipboard();
  1641. expect(clipboard).to.not.equal('Read permission denied.');
  1642. });
  1643. });
  1644. ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
  1645. let w: BrowserWindow;
  1646. const expectedBadgeCount = 42;
  1647. const fireAppBadgeAction: any = (action: string, value: any) => {
  1648. return w.webContents.executeJavaScript(`
  1649. navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
  1650. };
  1651. // For some reason on macOS changing the badge count doesn't happen right away, so wait
  1652. // until it changes.
  1653. async function waitForBadgeCount (value: number) {
  1654. let badgeCount = app.getBadgeCount();
  1655. while (badgeCount !== value) {
  1656. await new Promise(resolve => setTimeout(resolve, 10));
  1657. badgeCount = app.getBadgeCount();
  1658. }
  1659. return badgeCount;
  1660. }
  1661. describe('in the renderer', () => {
  1662. before(async () => {
  1663. w = new BrowserWindow({
  1664. show: false
  1665. });
  1666. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1667. });
  1668. after(() => {
  1669. app.badgeCount = 0;
  1670. closeAllWindows();
  1671. });
  1672. it('setAppBadge can set a numerical value', async () => {
  1673. const result = await fireAppBadgeAction('set', expectedBadgeCount);
  1674. expect(result).to.equal('success');
  1675. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1676. });
  1677. it('setAppBadge can set an empty(dot) value', async () => {
  1678. const result = await fireAppBadgeAction('set');
  1679. expect(result).to.equal('success');
  1680. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  1681. });
  1682. it('clearAppBadge can clear a value', async () => {
  1683. let result = await fireAppBadgeAction('set', expectedBadgeCount);
  1684. expect(result).to.equal('success');
  1685. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1686. result = await fireAppBadgeAction('clear');
  1687. expect(result).to.equal('success');
  1688. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  1689. });
  1690. });
  1691. describe('in a service worker', () => {
  1692. beforeEach(async () => {
  1693. w = new BrowserWindow({
  1694. show: false,
  1695. webPreferences: {
  1696. nodeIntegration: true,
  1697. partition: 'sw-file-scheme-spec',
  1698. contextIsolation: false
  1699. }
  1700. });
  1701. });
  1702. afterEach(() => {
  1703. app.badgeCount = 0;
  1704. closeAllWindows();
  1705. });
  1706. it('setAppBadge can be called in a ServiceWorker', (done) => {
  1707. w.webContents.on('ipc-message', (event, channel, message) => {
  1708. if (channel === 'reload') {
  1709. w.webContents.reload();
  1710. } else if (channel === 'error') {
  1711. done(message);
  1712. } else if (channel === 'response') {
  1713. expect(message).to.equal('SUCCESS setting app badge');
  1714. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1715. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  1716. storages: ['serviceworkers']
  1717. }).then(() => done());
  1718. }
  1719. });
  1720. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  1721. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
  1722. });
  1723. it('clearAppBadge can be called in a ServiceWorker', (done) => {
  1724. w.webContents.on('ipc-message', (event, channel, message) => {
  1725. if (channel === 'reload') {
  1726. w.webContents.reload();
  1727. } else if (channel === 'setAppBadge') {
  1728. expect(message).to.equal('SUCCESS setting app badge');
  1729. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1730. } else if (channel === 'error') {
  1731. done(message);
  1732. } else if (channel === 'response') {
  1733. expect(message).to.equal('SUCCESS clearing app badge');
  1734. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1735. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  1736. storages: ['serviceworkers']
  1737. }).then(() => done());
  1738. }
  1739. });
  1740. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  1741. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
  1742. });
  1743. });
  1744. });
  1745. describe('navigator.bluetooth', () => {
  1746. let w: BrowserWindow;
  1747. before(async () => {
  1748. w = new BrowserWindow({
  1749. show: false,
  1750. webPreferences: {
  1751. enableBlinkFeatures: 'WebBluetooth'
  1752. }
  1753. });
  1754. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1755. });
  1756. after(closeAllWindows);
  1757. it('can request bluetooth devices', async () => {
  1758. const bluetooth = await w.webContents.executeJavaScript(`
  1759. navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
  1760. expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
  1761. });
  1762. });
  1763. describe('navigator.hid', () => {
  1764. let w: BrowserWindow;
  1765. let server: http.Server;
  1766. let serverUrl: string;
  1767. before(async () => {
  1768. w = new BrowserWindow({
  1769. show: false
  1770. });
  1771. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1772. server = http.createServer((req, res) => {
  1773. res.setHeader('Content-Type', 'text/html');
  1774. res.end('<body>');
  1775. });
  1776. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1777. serverUrl = `http://localhost:${(server.address() as any).port}`;
  1778. });
  1779. const getDevices: any = () => {
  1780. return w.webContents.executeJavaScript(`
  1781. navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
  1782. `, true);
  1783. };
  1784. after(() => {
  1785. server.close();
  1786. closeAllWindows();
  1787. });
  1788. afterEach(() => {
  1789. session.defaultSession.setPermissionCheckHandler(null);
  1790. session.defaultSession.setDevicePermissionHandler(null);
  1791. session.defaultSession.removeAllListeners('select-hid-device');
  1792. });
  1793. it('does not return a device if select-hid-device event is not defined', async () => {
  1794. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1795. const device = await getDevices();
  1796. expect(device).to.equal('');
  1797. });
  1798. it('does not return a device when permission denied', async () => {
  1799. let selectFired = false;
  1800. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  1801. selectFired = true;
  1802. callback();
  1803. });
  1804. session.defaultSession.setPermissionCheckHandler(() => false);
  1805. const device = await getDevices();
  1806. expect(selectFired).to.be.false();
  1807. expect(device).to.equal('');
  1808. });
  1809. it('returns a device when select-hid-device event is defined', async () => {
  1810. let haveDevices = false;
  1811. let selectFired = false;
  1812. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  1813. expect(details.frame).to.have.ownProperty('frameTreeNodeId').that.is.a('number');
  1814. selectFired = true;
  1815. if (details.deviceList.length > 0) {
  1816. haveDevices = true;
  1817. callback(details.deviceList[0].deviceId);
  1818. } else {
  1819. callback();
  1820. }
  1821. });
  1822. const device = await getDevices();
  1823. expect(selectFired).to.be.true();
  1824. if (haveDevices) {
  1825. expect(device).to.contain('[object HIDDevice]');
  1826. } else {
  1827. expect(device).to.equal('');
  1828. }
  1829. if (process.arch === 'arm64' || process.arch === 'arm') {
  1830. // arm CI returns HID devices - this block may need to change if CI hardware changes.
  1831. expect(haveDevices).to.be.true();
  1832. // Verify that navigation will clear device permissions
  1833. const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  1834. expect(grantedDevices).to.not.be.empty();
  1835. w.loadURL(serverUrl);
  1836. const [,,,,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-navigate');
  1837. const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
  1838. expect(frame).to.not.be.empty();
  1839. if (frame) {
  1840. const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
  1841. expect(grantedDevicesOnNewPage).to.be.empty();
  1842. }
  1843. }
  1844. });
  1845. it('returns a device when DevicePermissionHandler is defined', async () => {
  1846. let haveDevices = false;
  1847. let selectFired = false;
  1848. let gotDevicePerms = false;
  1849. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  1850. selectFired = true;
  1851. if (details.deviceList.length > 0) {
  1852. const foundDevice = details.deviceList.find((device) => {
  1853. if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
  1854. haveDevices = true;
  1855. return true;
  1856. }
  1857. });
  1858. if (foundDevice) {
  1859. callback(foundDevice.deviceId);
  1860. return;
  1861. }
  1862. }
  1863. callback();
  1864. });
  1865. session.defaultSession.setDevicePermissionHandler(() => {
  1866. gotDevicePerms = true;
  1867. return true;
  1868. });
  1869. await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
  1870. const device = await getDevices();
  1871. expect(selectFired).to.be.true();
  1872. if (haveDevices) {
  1873. expect(device).to.contain('[object HIDDevice]');
  1874. expect(gotDevicePerms).to.be.true();
  1875. } else {
  1876. expect(device).to.equal('');
  1877. }
  1878. });
  1879. });