chromium-spec.ts 88 KB

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