chromium-spec.ts 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803
  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, itremote } from './spec-helpers';
  14. import { AddressInfo } from 'net';
  15. import { PipeTransport } from './pipe-transport';
  16. import * as ws from 'ws';
  17. const features = process._linkedBinding('electron_common_features');
  18. const fixturesPath = path.resolve(__dirname, 'fixtures');
  19. describe('reporting api', () => {
  20. // TODO(nornagon): this started failing a lot on CI. Figure out why and fix
  21. // it.
  22. it.skip('sends a report for a deprecation', async () => {
  23. const reports = new EventEmitter();
  24. // The Reporting API only works on https with valid certs. To dodge having
  25. // to set up a trusted certificate, hack the validator.
  26. session.defaultSession.setCertificateVerifyProc((req, cb) => {
  27. cb(0);
  28. });
  29. const certPath = path.join(fixturesPath, 'certificates');
  30. const options = {
  31. key: fs.readFileSync(path.join(certPath, 'server.key')),
  32. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  33. ca: [
  34. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  35. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  36. ],
  37. requestCert: true,
  38. rejectUnauthorized: false
  39. };
  40. const server = https.createServer(options, (req, res) => {
  41. if (req.url === '/report') {
  42. let data = '';
  43. req.on('data', (d) => { data += d.toString('utf-8'); });
  44. req.on('end', () => {
  45. reports.emit('report', JSON.parse(data));
  46. });
  47. }
  48. res.setHeader('Report-To', JSON.stringify({
  49. group: 'default',
  50. max_age: 120,
  51. endpoints: [{ url: `https://localhost:${(server.address() as any).port}/report` }]
  52. }));
  53. res.setHeader('Content-Type', 'text/html');
  54. // using the deprecated `webkitRequestAnimationFrame` will trigger a
  55. // "deprecation" report.
  56. res.end('<script>webkitRequestAnimationFrame(() => {})</script>');
  57. });
  58. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  59. const bw = new BrowserWindow({
  60. show: false
  61. });
  62. try {
  63. const reportGenerated = emittedOnce(reports, 'report');
  64. const url = `https://localhost:${(server.address() as any).port}/a`;
  65. await bw.loadURL(url);
  66. const [report] = await reportGenerated;
  67. expect(report).to.be.an('array');
  68. expect(report[0].type).to.equal('deprecation');
  69. expect(report[0].url).to.equal(url);
  70. expect(report[0].body.id).to.equal('PrefixedRequestAnimationFrame');
  71. } finally {
  72. bw.destroy();
  73. server.close();
  74. }
  75. });
  76. });
  77. describe('window.postMessage', () => {
  78. afterEach(async () => {
  79. await closeAllWindows();
  80. });
  81. it('sets the source and origin correctly', async () => {
  82. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  83. w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`);
  84. const [, message] = await emittedOnce(ipcMain, 'complete');
  85. expect(message.data).to.equal('testing');
  86. expect(message.origin).to.equal('file://');
  87. expect(message.sourceEqualsOpener).to.equal(true);
  88. expect(message.eventOrigin).to.equal('file://');
  89. });
  90. });
  91. describe('focus handling', () => {
  92. let webviewContents: WebContents = null as unknown as WebContents;
  93. let w: BrowserWindow = null as unknown as BrowserWindow;
  94. beforeEach(async () => {
  95. w = new BrowserWindow({
  96. show: true,
  97. webPreferences: {
  98. nodeIntegration: true,
  99. webviewTag: true,
  100. contextIsolation: false
  101. }
  102. });
  103. const webviewReady = emittedOnce(w.webContents, 'did-attach-webview');
  104. await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html'));
  105. const [, wvContents] = await webviewReady;
  106. webviewContents = wvContents;
  107. await emittedOnce(webviewContents, 'did-finish-load');
  108. w.focus();
  109. });
  110. afterEach(() => {
  111. webviewContents = null as unknown as WebContents;
  112. w.destroy();
  113. w = null as unknown as BrowserWindow;
  114. });
  115. const expectFocusChange = async () => {
  116. const [, focusedElementId] = await emittedOnce(ipcMain, 'focus-changed');
  117. return focusedElementId;
  118. };
  119. describe('a TAB press', () => {
  120. const tabPressEvent: any = {
  121. type: 'keyDown',
  122. keyCode: 'Tab'
  123. };
  124. it('moves focus to the next focusable item', async () => {
  125. let focusChange = expectFocusChange();
  126. w.webContents.sendInputEvent(tabPressEvent);
  127. let focusedElementId = await focusChange;
  128. expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`);
  129. focusChange = expectFocusChange();
  130. w.webContents.sendInputEvent(tabPressEvent);
  131. focusedElementId = await focusChange;
  132. expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
  133. focusChange = expectFocusChange();
  134. w.webContents.sendInputEvent(tabPressEvent);
  135. focusedElementId = await focusChange;
  136. expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
  137. focusChange = expectFocusChange();
  138. webviewContents.sendInputEvent(tabPressEvent);
  139. focusedElementId = await focusChange;
  140. expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
  141. focusChange = expectFocusChange();
  142. webviewContents.sendInputEvent(tabPressEvent);
  143. focusedElementId = await focusChange;
  144. expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`);
  145. focusChange = expectFocusChange();
  146. w.webContents.sendInputEvent(tabPressEvent);
  147. focusedElementId = await focusChange;
  148. expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`);
  149. });
  150. });
  151. describe('a SHIFT + TAB press', () => {
  152. const shiftTabPressEvent: any = {
  153. type: 'keyDown',
  154. modifiers: ['Shift'],
  155. keyCode: 'Tab'
  156. };
  157. it('moves focus to the previous focusable item', async () => {
  158. let focusChange = expectFocusChange();
  159. w.webContents.sendInputEvent(shiftTabPressEvent);
  160. let focusedElementId = await focusChange;
  161. expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`);
  162. focusChange = expectFocusChange();
  163. w.webContents.sendInputEvent(shiftTabPressEvent);
  164. focusedElementId = await focusChange;
  165. expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
  166. focusChange = expectFocusChange();
  167. webviewContents.sendInputEvent(shiftTabPressEvent);
  168. focusedElementId = await focusChange;
  169. expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
  170. focusChange = expectFocusChange();
  171. webviewContents.sendInputEvent(shiftTabPressEvent);
  172. focusedElementId = await focusChange;
  173. expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
  174. focusChange = expectFocusChange();
  175. w.webContents.sendInputEvent(shiftTabPressEvent);
  176. focusedElementId = await focusChange;
  177. expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`);
  178. focusChange = expectFocusChange();
  179. w.webContents.sendInputEvent(shiftTabPressEvent);
  180. focusedElementId = await focusChange;
  181. expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`);
  182. });
  183. });
  184. });
  185. describe('web security', () => {
  186. afterEach(closeAllWindows);
  187. let server: http.Server;
  188. let serverUrl: string;
  189. before(async () => {
  190. server = http.createServer((req, res) => {
  191. res.setHeader('Content-Type', 'text/html');
  192. res.end('<body>');
  193. });
  194. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  195. serverUrl = `http://localhost:${(server.address() as any).port}`;
  196. });
  197. after(() => {
  198. server.close();
  199. });
  200. it('engages CORB when web security is not disabled', async () => {
  201. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
  202. const p = emittedOnce(ipcMain, 'success');
  203. await w.loadURL(`data:text/html,<script>
  204. const s = document.createElement('script')
  205. s.src = "${serverUrl}"
  206. // The script will load successfully but its body will be emptied out
  207. // by CORB, so we don't expect a syntax error.
  208. s.onload = () => { require('electron').ipcRenderer.send('success') }
  209. document.documentElement.appendChild(s)
  210. </script>`);
  211. await p;
  212. });
  213. it('bypasses CORB when web security is disabled', async () => {
  214. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
  215. const p = emittedOnce(ipcMain, 'success');
  216. await w.loadURL(`data:text/html,
  217. <script>
  218. window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) }
  219. </script>
  220. <script src="${serverUrl}"></script>`);
  221. await p;
  222. });
  223. it('engages CORS when web security is not disabled', async () => {
  224. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
  225. const p = emittedOnce(ipcMain, 'response');
  226. await w.loadURL(`data:text/html,<script>
  227. (async function() {
  228. try {
  229. await fetch('${serverUrl}');
  230. require('electron').ipcRenderer.send('response', 'passed');
  231. } catch {
  232. require('electron').ipcRenderer.send('response', 'failed');
  233. }
  234. })();
  235. </script>`);
  236. const [, response] = await p;
  237. expect(response).to.equal('failed');
  238. });
  239. it('bypasses CORS when web security is disabled', async () => {
  240. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
  241. const p = emittedOnce(ipcMain, 'response');
  242. await w.loadURL(`data:text/html,<script>
  243. (async function() {
  244. try {
  245. await fetch('${serverUrl}');
  246. require('electron').ipcRenderer.send('response', 'passed');
  247. } catch {
  248. require('electron').ipcRenderer.send('response', 'failed');
  249. }
  250. })();
  251. </script>`);
  252. const [, response] = await p;
  253. expect(response).to.equal('passed');
  254. });
  255. describe('accessing file://', () => {
  256. async function loadFile (w: BrowserWindow) {
  257. const thisFile = url.format({
  258. pathname: __filename.replace(/\\/g, '/'),
  259. protocol: 'file',
  260. slashes: true
  261. });
  262. await w.loadURL(`data:text/html,<script>
  263. function loadFile() {
  264. return new Promise((resolve) => {
  265. fetch('${thisFile}').then(
  266. () => resolve('loaded'),
  267. () => resolve('failed')
  268. )
  269. });
  270. }
  271. </script>`);
  272. return await w.webContents.executeJavaScript('loadFile()');
  273. }
  274. it('is forbidden when web security is enabled', async () => {
  275. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } });
  276. const result = await loadFile(w);
  277. expect(result).to.equal('failed');
  278. });
  279. it('is allowed when web security is disabled', async () => {
  280. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } });
  281. const result = await loadFile(w);
  282. expect(result).to.equal('loaded');
  283. });
  284. });
  285. describe('wasm-eval csp', () => {
  286. async function loadWasm (csp: string) {
  287. const w = new BrowserWindow({
  288. show: false,
  289. webPreferences: {
  290. sandbox: true,
  291. enableBlinkFeatures: 'WebAssemblyCSP'
  292. }
  293. });
  294. await w.loadURL(`data:text/html,<head>
  295. <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}">
  296. </head>
  297. <script>
  298. function loadWasm() {
  299. const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
  300. return new Promise((resolve) => {
  301. WebAssembly.instantiate(wasmBin).then(() => {
  302. resolve('loaded')
  303. }).catch((error) => {
  304. resolve(error.message)
  305. })
  306. });
  307. }
  308. </script>`);
  309. return await w.webContents.executeJavaScript('loadWasm()');
  310. }
  311. it('wasm codegen is disallowed by default', async () => {
  312. const r = await loadWasm('');
  313. expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"');
  314. });
  315. it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => {
  316. const r = await loadWasm("'wasm-unsafe-eval'");
  317. expect(r).to.equal('loaded');
  318. });
  319. });
  320. it('does not crash when multiple WebContent are created with web security disabled', () => {
  321. const options = { show: false, webPreferences: { webSecurity: false } };
  322. const w1 = new BrowserWindow(options);
  323. w1.loadURL(serverUrl);
  324. const w2 = new BrowserWindow(options);
  325. w2.loadURL(serverUrl);
  326. });
  327. });
  328. describe('command line switches', () => {
  329. let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
  330. afterEach(() => {
  331. if (appProcess && !appProcess.killed) {
  332. appProcess.kill();
  333. appProcess = undefined;
  334. }
  335. });
  336. describe('--lang switch', () => {
  337. const currentLocale = app.getLocale();
  338. const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
  339. const appPath = path.join(fixturesPath, 'api', 'locale-check');
  340. const args = [appPath, `--set-lang=${locale}`];
  341. if (printEnv) {
  342. args.push('--print-env');
  343. }
  344. appProcess = ChildProcess.spawn(process.execPath, args);
  345. let output = '';
  346. appProcess.stdout.on('data', (data) => { output += data; });
  347. let stderr = '';
  348. appProcess.stderr.on('data', (data) => { stderr += data; });
  349. const [code, signal] = await emittedOnce(appProcess, 'exit');
  350. if (code !== 0) {
  351. throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
  352. }
  353. output = output.replace(/(\r\n|\n|\r)/gm, '');
  354. expect(output).to.equal(result);
  355. };
  356. it('should set the locale', async () => testLocale('fr', 'fr'));
  357. it('should not set an invalid locale', async () => testLocale('asdfkl', currentLocale));
  358. const lcAll = String(process.env.LC_ALL);
  359. ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
  360. // The LC_ALL env should not be set to DOM locale string.
  361. expect(lcAll).to.not.equal(app.getLocale());
  362. });
  363. ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
  364. ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
  365. ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
  366. });
  367. describe('--remote-debugging-pipe switch', () => {
  368. it('should expose CDP via pipe', async () => {
  369. const electronPath = process.execPath;
  370. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
  371. stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
  372. }) as ChildProcess.ChildProcessWithoutNullStreams;
  373. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  374. const pipe = new PipeTransport(stdio[3], stdio[4]);
  375. const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
  376. pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
  377. const message = (await versionPromise) as any;
  378. expect(message.id).to.equal(1);
  379. expect(message.result.product).to.contain('Chrome');
  380. expect(message.result.userAgent).to.contain('Electron');
  381. });
  382. it('should override --remote-debugging-port switch', async () => {
  383. const electronPath = process.execPath;
  384. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], {
  385. stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe']
  386. }) as ChildProcess.ChildProcessWithoutNullStreams;
  387. let stderr = '';
  388. appProcess.stderr.on('data', (data: string) => { stderr += data; });
  389. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  390. const pipe = new PipeTransport(stdio[3], stdio[4]);
  391. const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
  392. pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
  393. const message = (await versionPromise) as any;
  394. expect(message.id).to.equal(1);
  395. expect(stderr).to.not.include('DevTools listening on');
  396. });
  397. it('should shut down Electron upon Browser.close CDP command', async () => {
  398. const electronPath = process.execPath;
  399. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
  400. stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
  401. }) as ChildProcess.ChildProcessWithoutNullStreams;
  402. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  403. const pipe = new PipeTransport(stdio[3], stdio[4]);
  404. pipe.send({ id: 1, method: 'Browser.close', params: {} });
  405. await new Promise(resolve => { appProcess!.on('exit', resolve); });
  406. });
  407. });
  408. describe('--remote-debugging-port switch', () => {
  409. it('should display the discovery page', (done) => {
  410. const electronPath = process.execPath;
  411. let output = '';
  412. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']);
  413. appProcess.stdout.on('data', (data) => {
  414. console.log(data);
  415. });
  416. appProcess.stderr.on('data', (data) => {
  417. console.log(data);
  418. output += data;
  419. const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
  420. if (m) {
  421. appProcess!.stderr.removeAllListeners('data');
  422. const port = m[1];
  423. http.get(`http://127.0.0.1:${port}`, (res) => {
  424. try {
  425. expect(res.statusCode).to.eql(200);
  426. expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
  427. done();
  428. } catch (e) {
  429. done(e);
  430. } finally {
  431. res.destroy();
  432. }
  433. });
  434. }
  435. });
  436. });
  437. });
  438. });
  439. describe('chromium features', () => {
  440. afterEach(closeAllWindows);
  441. describe('accessing key names also used as Node.js module names', () => {
  442. it('does not crash', (done) => {
  443. const w = new BrowserWindow({ show: false });
  444. w.webContents.once('did-finish-load', () => { done(); });
  445. w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
  446. w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
  447. });
  448. });
  449. describe('first party sets', () => {
  450. const fps = [
  451. 'https://fps-member1.glitch.me',
  452. 'https://fps-member2.glitch.me',
  453. 'https://fps-member3.glitch.me'
  454. ];
  455. it('loads first party sets', async () => {
  456. const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base');
  457. const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]);
  458. let output = '';
  459. fpsProcess.stdout.on('data', data => { output += data; });
  460. await emittedOnce(fpsProcess, 'exit');
  461. expect(output).to.include(fps.join(','));
  462. });
  463. it('loads sets from the command line', async () => {
  464. const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line');
  465. const args = [appPath, `--use-first-party-set=${fps}`];
  466. const fpsProcess = ChildProcess.spawn(process.execPath, args);
  467. let output = '';
  468. fpsProcess.stdout.on('data', data => { output += data; });
  469. await emittedOnce(fpsProcess, 'exit');
  470. expect(output).to.include(fps.join(','));
  471. });
  472. });
  473. describe('loading jquery', () => {
  474. it('does not crash', (done) => {
  475. const w = new BrowserWindow({ show: false });
  476. w.webContents.once('did-finish-load', () => { done(); });
  477. w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
  478. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
  479. });
  480. });
  481. describe('navigator.languages', () => {
  482. it('should return the system locale only', async () => {
  483. const appLocale = app.getLocale();
  484. const w = new BrowserWindow({ show: false });
  485. await w.loadURL('about:blank');
  486. const languages = await w.webContents.executeJavaScript('navigator.languages');
  487. expect(languages.length).to.be.greaterThan(0);
  488. expect(languages).to.contain(appLocale);
  489. });
  490. });
  491. describe('navigator.serviceWorker', () => {
  492. it('should register for file scheme', (done) => {
  493. const w = new BrowserWindow({
  494. show: false,
  495. webPreferences: {
  496. nodeIntegration: true,
  497. partition: 'sw-file-scheme-spec',
  498. contextIsolation: false
  499. }
  500. });
  501. w.webContents.on('ipc-message', (event, channel, message) => {
  502. if (channel === 'reload') {
  503. w.webContents.reload();
  504. } else if (channel === 'error') {
  505. done(message);
  506. } else if (channel === 'response') {
  507. expect(message).to.equal('Hello from serviceWorker!');
  508. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  509. storages: ['serviceworkers']
  510. }).then(() => done());
  511. }
  512. });
  513. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  514. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  515. });
  516. it('should register for intercepted file scheme', (done) => {
  517. const customSession = session.fromPartition('intercept-file');
  518. customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
  519. let file = url.parse(request.url).pathname!;
  520. if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
  521. const content = fs.readFileSync(path.normalize(file));
  522. const ext = path.extname(file);
  523. let type = 'text/html';
  524. if (ext === '.js') type = 'application/javascript';
  525. callback({ data: content, mimeType: type } as any);
  526. });
  527. const w = new BrowserWindow({
  528. show: false,
  529. webPreferences: {
  530. nodeIntegration: true,
  531. session: customSession,
  532. contextIsolation: false
  533. }
  534. });
  535. w.webContents.on('ipc-message', (event, channel, message) => {
  536. if (channel === 'reload') {
  537. w.webContents.reload();
  538. } else if (channel === 'error') {
  539. done(`unexpected error : ${message}`);
  540. } else if (channel === 'response') {
  541. expect(message).to.equal('Hello from serviceWorker!');
  542. customSession.clearStorageData({
  543. storages: ['serviceworkers']
  544. }).then(() => {
  545. customSession.protocol.uninterceptProtocol('file');
  546. done();
  547. });
  548. }
  549. });
  550. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  551. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  552. });
  553. it('should register for custom scheme', (done) => {
  554. const customSession = session.fromPartition('custom-scheme');
  555. customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => {
  556. let file = url.parse(request.url).pathname!;
  557. if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
  558. callback({ path: path.normalize(file) } as any);
  559. });
  560. const w = new BrowserWindow({
  561. show: false,
  562. webPreferences: {
  563. nodeIntegration: true,
  564. session: customSession,
  565. contextIsolation: false
  566. }
  567. });
  568. w.webContents.on('ipc-message', (event, channel, message) => {
  569. if (channel === 'reload') {
  570. w.webContents.reload();
  571. } else if (channel === 'error') {
  572. done(`unexpected error : ${message}`);
  573. } else if (channel === 'response') {
  574. expect(message).to.equal('Hello from serviceWorker!');
  575. customSession.clearStorageData({
  576. storages: ['serviceworkers']
  577. }).then(() => {
  578. customSession.protocol.uninterceptProtocol(serviceWorkerScheme);
  579. done();
  580. });
  581. }
  582. });
  583. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  584. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html'));
  585. });
  586. it('should not crash when nodeIntegration is enabled', (done) => {
  587. const w = new BrowserWindow({
  588. show: false,
  589. webPreferences: {
  590. nodeIntegration: true,
  591. nodeIntegrationInWorker: true,
  592. partition: 'sw-file-scheme-worker-spec',
  593. contextIsolation: false
  594. }
  595. });
  596. w.webContents.on('ipc-message', (event, channel, message) => {
  597. if (channel === 'reload') {
  598. w.webContents.reload();
  599. } else if (channel === 'error') {
  600. done(`unexpected error : ${message}`);
  601. } else if (channel === 'response') {
  602. expect(message).to.equal('Hello from serviceWorker!');
  603. session.fromPartition('sw-file-scheme-worker-spec').clearStorageData({
  604. storages: ['serviceworkers']
  605. }).then(() => done());
  606. }
  607. });
  608. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  609. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  610. });
  611. });
  612. ifdescribe(features.isFakeLocationProviderEnabled())('navigator.geolocation', () => {
  613. it('returns error when permission is denied', async () => {
  614. const w = new BrowserWindow({
  615. show: false,
  616. webPreferences: {
  617. nodeIntegration: true,
  618. partition: 'geolocation-spec',
  619. contextIsolation: false
  620. }
  621. });
  622. const message = emittedOnce(w.webContents, 'ipc-message');
  623. w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
  624. if (permission === 'geolocation') {
  625. callback(false);
  626. } else {
  627. callback(true);
  628. }
  629. });
  630. w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
  631. const [, channel] = await message;
  632. expect(channel).to.equal('success', 'unexpected response from geolocation api');
  633. });
  634. it('returns position when permission is granted', async () => {
  635. const w = new BrowserWindow({ show: false });
  636. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  637. const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) =>
  638. navigator.geolocation.getCurrentPosition(
  639. x => resolve({coords: x.coords, timestamp: x.timestamp}),
  640. reject))`);
  641. expect(position).to.have.property('coords');
  642. expect(position).to.have.property('timestamp');
  643. });
  644. });
  645. describe('web workers', () => {
  646. let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
  647. afterEach(() => {
  648. if (appProcess && !appProcess.killed) {
  649. appProcess.kill();
  650. appProcess = undefined;
  651. }
  652. });
  653. it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => {
  654. const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths');
  655. appProcess = ChildProcess.spawn(process.execPath, [appPath]);
  656. const [code] = await emittedOnce(appProcess, 'exit');
  657. expect(code).to.equal(0);
  658. });
  659. it('Worker can work', async () => {
  660. const w = new BrowserWindow({ show: false });
  661. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  662. const data = await w.webContents.executeJavaScript(`
  663. const worker = new Worker('../workers/worker.js');
  664. const message = 'ping';
  665. const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; });
  666. worker.postMessage(message);
  667. eventPromise.then(t => t.data)
  668. `);
  669. expect(data).to.equal('ping');
  670. });
  671. it('Worker has no node integration by default', async () => {
  672. const w = new BrowserWindow({ show: false });
  673. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  674. const data = await w.webContents.executeJavaScript(`
  675. const worker = new Worker('../workers/worker_node.js');
  676. new Promise((resolve) => { worker.onmessage = e => resolve(e.data); })
  677. `);
  678. expect(data).to.equal('undefined undefined undefined undefined');
  679. });
  680. it('Worker has node integration with nodeIntegrationInWorker', async () => {
  681. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } });
  682. w.loadURL(`file://${fixturesPath}/pages/worker.html`);
  683. const [, data] = await emittedOnce(ipcMain, 'worker-result');
  684. expect(data).to.equal('object function object function');
  685. });
  686. describe('SharedWorker', () => {
  687. it('can work', async () => {
  688. const w = new BrowserWindow({ show: false });
  689. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  690. const data = await w.webContents.executeJavaScript(`
  691. const worker = new SharedWorker('../workers/shared_worker.js');
  692. const message = 'ping';
  693. const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); });
  694. worker.port.postMessage(message);
  695. eventPromise
  696. `);
  697. expect(data).to.equal('ping');
  698. });
  699. it('has no node integration by default', async () => {
  700. const w = new BrowserWindow({ show: false });
  701. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  702. const data = await w.webContents.executeJavaScript(`
  703. const worker = new SharedWorker('../workers/shared_worker_node.js');
  704. new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
  705. `);
  706. expect(data).to.equal('undefined undefined undefined undefined');
  707. });
  708. it('has node integration with nodeIntegrationInWorker', async () => {
  709. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } });
  710. w.loadURL(`file://${fixturesPath}/pages/shared_worker.html`);
  711. const [, data] = await emittedOnce(ipcMain, 'worker-result');
  712. expect(data).to.equal('object function object function');
  713. });
  714. });
  715. });
  716. describe('form submit', () => {
  717. let server: http.Server;
  718. let serverUrl: string;
  719. before(async () => {
  720. server = http.createServer((req, res) => {
  721. let body = '';
  722. req.on('data', (chunk) => {
  723. body += chunk;
  724. });
  725. res.setHeader('Content-Type', 'application/json');
  726. req.on('end', () => {
  727. res.end(`body:${body}`);
  728. });
  729. });
  730. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  731. serverUrl = `http://localhost:${(server.address() as any).port}`;
  732. });
  733. after(async () => {
  734. server.close();
  735. await closeAllWindows();
  736. });
  737. [true, false].forEach((isSandboxEnabled) =>
  738. describe(`sandbox=${isSandboxEnabled}`, () => {
  739. it('posts data in the same window', async () => {
  740. const w = new BrowserWindow({
  741. show: false,
  742. webPreferences: {
  743. sandbox: isSandboxEnabled
  744. }
  745. });
  746. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  747. const loadPromise = emittedOnce(w.webContents, 'did-finish-load');
  748. w.webContents.executeJavaScript(`
  749. const form = document.querySelector('form')
  750. form.action = '${serverUrl}';
  751. form.submit();
  752. `);
  753. await loadPromise;
  754. const res = await w.webContents.executeJavaScript('document.body.innerText');
  755. expect(res).to.equal('body:greeting=hello');
  756. });
  757. it('posts data to a new window with target=_blank', async () => {
  758. const w = new BrowserWindow({
  759. show: false,
  760. webPreferences: {
  761. sandbox: isSandboxEnabled
  762. }
  763. });
  764. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  765. const windowCreatedPromise = emittedOnce(app, 'browser-window-created');
  766. w.webContents.executeJavaScript(`
  767. const form = document.querySelector('form')
  768. form.action = '${serverUrl}';
  769. form.target = '_blank';
  770. form.submit();
  771. `);
  772. const [, newWin] = await windowCreatedPromise;
  773. const res = await newWin.webContents.executeJavaScript('document.body.innerText');
  774. expect(res).to.equal('body:greeting=hello');
  775. });
  776. })
  777. );
  778. });
  779. describe('window.open', () => {
  780. for (const show of [true, false]) {
  781. it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => {
  782. const w = new BrowserWindow({ show });
  783. // toggle visibility
  784. if (show) {
  785. w.hide();
  786. } else {
  787. w.show();
  788. }
  789. defer(() => { w.close(); });
  790. const promise = emittedOnce(app, 'browser-window-created');
  791. w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
  792. const [, newWindow] = await promise;
  793. expect(newWindow.isVisible()).to.equal(true);
  794. });
  795. }
  796. // FIXME(zcbenz): This test is making the spec runner hang on exit on Windows.
  797. ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => {
  798. const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html'));
  799. windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`);
  800. const w = new BrowserWindow({ show: false });
  801. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  802. const { eventData } = await w.webContents.executeJavaScript(`(async () => {
  803. const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
  804. const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false')
  805. const e = await message
  806. b.close();
  807. return {
  808. eventData: e.data
  809. }
  810. })()`);
  811. expect(eventData.isProcessGlobalUndefined).to.be.true();
  812. });
  813. it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
  814. // NB. webSecurity is disabled because native window.open() is not
  815. // allowed to load devtools:// URLs.
  816. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } });
  817. w.loadURL('about:blank');
  818. w.webContents.executeJavaScript(`
  819. { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null }
  820. `);
  821. const [, contents] = await emittedOnce(app, 'web-contents-created');
  822. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  823. expect(typeofProcessGlobal).to.equal('undefined');
  824. });
  825. it('can disable node integration when it is enabled on the parent window', async () => {
  826. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  827. w.loadURL('about:blank');
  828. w.webContents.executeJavaScript(`
  829. { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null }
  830. `);
  831. const [, contents] = await emittedOnce(app, 'web-contents-created');
  832. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  833. expect(typeofProcessGlobal).to.equal('undefined');
  834. });
  835. // TODO(jkleinsc) fix this flaky test on WOA
  836. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => {
  837. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } });
  838. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  839. const windowUrl = require('url').format({
  840. pathname: `${fixturesPath}/pages/window-no-javascript.html`,
  841. protocol: 'file',
  842. slashes: true
  843. });
  844. w.webContents.executeJavaScript(`
  845. { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null }
  846. `);
  847. const [, contents] = await emittedOnce(app, 'web-contents-created');
  848. await emittedOnce(contents, 'did-finish-load');
  849. // Click link on page
  850. contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
  851. contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
  852. const [, window] = await emittedOnce(app, 'browser-window-created');
  853. const preferences = window.webContents.getLastWebPreferences();
  854. expect(preferences.javascript).to.be.false();
  855. });
  856. it('defines a window.location getter', async () => {
  857. let targetURL: string;
  858. if (process.platform === 'win32') {
  859. targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
  860. } else {
  861. targetURL = `file://${fixturesPath}/pages/base-page.html`;
  862. }
  863. const w = new BrowserWindow({ show: false });
  864. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  865. w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
  866. const [, window] = await emittedOnce(app, 'browser-window-created');
  867. await emittedOnce(window.webContents, 'did-finish-load');
  868. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
  869. });
  870. it('defines a window.location setter', async () => {
  871. const w = new BrowserWindow({ show: false });
  872. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  873. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  874. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  875. await emittedOnce(webContents, 'did-finish-load');
  876. // When it loads, redirect
  877. w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  878. await emittedOnce(webContents, 'did-finish-load');
  879. });
  880. it('defines a window.location.href setter', async () => {
  881. const w = new BrowserWindow({ show: false });
  882. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  883. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  884. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  885. await emittedOnce(webContents, 'did-finish-load');
  886. // When it loads, redirect
  887. w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  888. await emittedOnce(webContents, 'did-finish-load');
  889. });
  890. it('open a blank page when no URL is specified', async () => {
  891. const w = new BrowserWindow({ show: false });
  892. w.loadURL('about:blank');
  893. w.webContents.executeJavaScript('{ b = window.open(); null }');
  894. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  895. await emittedOnce(webContents, 'did-finish-load');
  896. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  897. });
  898. it('open a blank page when an empty URL is specified', async () => {
  899. const w = new BrowserWindow({ show: false });
  900. w.loadURL('about:blank');
  901. w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
  902. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  903. await emittedOnce(webContents, 'did-finish-load');
  904. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  905. });
  906. it('does not throw an exception when the frameName is a built-in object property', async () => {
  907. const w = new BrowserWindow({ show: false });
  908. w.loadURL('about:blank');
  909. w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
  910. const frameName = await new Promise((resolve) => {
  911. w.webContents.setWindowOpenHandler(details => {
  912. setImmediate(() => resolve(details.frameName));
  913. return { action: 'allow' };
  914. });
  915. });
  916. expect(frameName).to.equal('__proto__');
  917. });
  918. // TODO(nornagon): I'm not sure this ... ever was correct?
  919. it.skip('inherit options of parent window', async () => {
  920. const w = new BrowserWindow({ show: false, width: 123, height: 456 });
  921. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  922. const url = `file://${fixturesPath}/pages/window-open-size.html`;
  923. const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => {
  924. const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
  925. const b = window.open(${JSON.stringify(url)}, '', 'show=false')
  926. const e = await message
  927. b.close();
  928. const width = outerWidth;
  929. const height = outerHeight;
  930. return {
  931. width,
  932. height,
  933. eventData: e.data
  934. }
  935. })()`);
  936. expect(eventData).to.equal(`size: ${width} ${height}`);
  937. expect(eventData).to.equal('size: 123 456');
  938. });
  939. it('does not override child options', async () => {
  940. const w = new BrowserWindow({ show: false });
  941. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  942. const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`;
  943. const { eventData } = await w.webContents.executeJavaScript(`(async () => {
  944. const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
  945. const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450')
  946. const e = await message
  947. b.close();
  948. return { eventData: e.data }
  949. })()`);
  950. expect(eventData).to.equal('size: 350 450');
  951. });
  952. it('disables the <webview> tag when it is disabled on the parent window', async () => {
  953. const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html'));
  954. windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`);
  955. const w = new BrowserWindow({ show: false });
  956. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  957. const { eventData } = await w.webContents.executeJavaScript(`(async () => {
  958. const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
  959. const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no')
  960. const e = await message
  961. b.close();
  962. return { eventData: e.data }
  963. })()`);
  964. expect(eventData.isWebViewGlobalUndefined).to.be.true();
  965. });
  966. it('throws an exception when the arguments cannot be converted to strings', async () => {
  967. const w = new BrowserWindow({ show: false });
  968. w.loadURL('about:blank');
  969. await expect(
  970. w.webContents.executeJavaScript('window.open(\'\', { toString: null })')
  971. ).to.eventually.be.rejected();
  972. await expect(
  973. w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })')
  974. ).to.eventually.be.rejected();
  975. });
  976. it('does not throw an exception when the features include webPreferences', async () => {
  977. const w = new BrowserWindow({ show: false });
  978. w.loadURL('about:blank');
  979. await expect(
  980. w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null')
  981. ).to.eventually.be.fulfilled();
  982. });
  983. });
  984. describe('window.opener', () => {
  985. it('is null for main window', async () => {
  986. const w = new BrowserWindow({
  987. show: false,
  988. webPreferences: {
  989. nodeIntegration: true,
  990. contextIsolation: false
  991. }
  992. });
  993. w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
  994. const [, channel, opener] = await emittedOnce(w.webContents, 'ipc-message');
  995. expect(channel).to.equal('opener');
  996. expect(opener).to.equal(null);
  997. });
  998. it('is not null for window opened by window.open', async () => {
  999. const w = new BrowserWindow({
  1000. show: false,
  1001. webPreferences: {
  1002. nodeIntegration: true,
  1003. contextIsolation: false
  1004. }
  1005. });
  1006. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  1007. const windowUrl = `file://${fixturesPath}/pages/window-opener.html`;
  1008. const eventData = await w.webContents.executeJavaScript(`
  1009. const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
  1010. new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data);
  1011. `);
  1012. expect(eventData).to.equal('object');
  1013. });
  1014. });
  1015. describe('window.opener.postMessage', () => {
  1016. it('sets source and origin correctly', async () => {
  1017. const w = new BrowserWindow({ show: false });
  1018. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  1019. const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`;
  1020. const { sourceIsChild, origin } = await w.webContents.executeJavaScript(`
  1021. const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
  1022. new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({
  1023. sourceIsChild: e.source === b,
  1024. origin: e.origin
  1025. }));
  1026. `);
  1027. expect(sourceIsChild).to.be.true();
  1028. expect(origin).to.equal('file://');
  1029. });
  1030. it('supports windows opened from a <webview>', async () => {
  1031. const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
  1032. w.loadURL('about:blank');
  1033. const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html'));
  1034. childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`);
  1035. const message = await w.webContents.executeJavaScript(`
  1036. const webview = new WebView();
  1037. webview.allowpopups = true;
  1038. webview.setAttribute('webpreferences', 'contextIsolation=no');
  1039. webview.src = ${JSON.stringify(childWindowUrl)}
  1040. const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true}));
  1041. document.body.appendChild(webview);
  1042. consoleMessage.then(e => e.message)
  1043. `);
  1044. expect(message).to.equal('message');
  1045. });
  1046. describe('targetOrigin argument', () => {
  1047. let serverURL: string;
  1048. let server: any;
  1049. beforeEach((done) => {
  1050. server = http.createServer((req, res) => {
  1051. res.writeHead(200);
  1052. const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html');
  1053. res.end(fs.readFileSync(filePath, 'utf8'));
  1054. });
  1055. server.listen(0, '127.0.0.1', () => {
  1056. serverURL = `http://127.0.0.1:${server.address().port}`;
  1057. done();
  1058. });
  1059. });
  1060. afterEach(() => {
  1061. server.close();
  1062. });
  1063. it('delivers messages that match the origin', async () => {
  1064. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1065. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  1066. const data = await w.webContents.executeJavaScript(`
  1067. window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes');
  1068. new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data)
  1069. `);
  1070. expect(data).to.equal('deliver');
  1071. });
  1072. });
  1073. });
  1074. describe('navigator.mediaDevices', () => {
  1075. afterEach(closeAllWindows);
  1076. afterEach(() => {
  1077. session.defaultSession.setPermissionCheckHandler(null);
  1078. session.defaultSession.setPermissionRequestHandler(null);
  1079. });
  1080. it('can return labels of enumerated devices', async () => {
  1081. const w = new BrowserWindow({ show: false });
  1082. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1083. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  1084. expect(labels.some((l: any) => l)).to.be.true();
  1085. });
  1086. it('does not return labels of enumerated devices when permission denied', async () => {
  1087. session.defaultSession.setPermissionCheckHandler(() => false);
  1088. const w = new BrowserWindow({ show: false });
  1089. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1090. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  1091. expect(labels.some((l: any) => l)).to.be.false();
  1092. });
  1093. it('returns the same device ids across reloads', async () => {
  1094. const ses = session.fromPartition('persist:media-device-id');
  1095. const w = new BrowserWindow({
  1096. show: false,
  1097. webPreferences: {
  1098. nodeIntegration: true,
  1099. session: ses,
  1100. contextIsolation: false
  1101. }
  1102. });
  1103. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  1104. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  1105. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  1106. expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
  1107. });
  1108. it('can return new device id when cookie storage is cleared', async () => {
  1109. const ses = session.fromPartition('persist:media-device-id');
  1110. const w = new BrowserWindow({
  1111. show: false,
  1112. webPreferences: {
  1113. nodeIntegration: true,
  1114. session: ses,
  1115. contextIsolation: false
  1116. }
  1117. });
  1118. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  1119. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  1120. await ses.clearStorageData({ storages: ['cookies'] });
  1121. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  1122. expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
  1123. });
  1124. it('provides a securityOrigin to the request handler', async () => {
  1125. session.defaultSession.setPermissionRequestHandler(
  1126. (wc, permission, callback, details) => {
  1127. if (details.securityOrigin !== undefined) {
  1128. callback(true);
  1129. } else {
  1130. callback(false);
  1131. }
  1132. }
  1133. );
  1134. const w = new BrowserWindow({ show: false });
  1135. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1136. const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({
  1137. video: {
  1138. mandatory: {
  1139. chromeMediaSource: "desktop",
  1140. minWidth: 1280,
  1141. maxWidth: 1280,
  1142. minHeight: 720,
  1143. maxHeight: 720
  1144. }
  1145. }
  1146. }).then((stream) => stream.getVideoTracks())`);
  1147. expect(labels.some((l: any) => l)).to.be.true();
  1148. });
  1149. it('fails with "not supported" for getDisplayMedia', async () => {
  1150. const w = new BrowserWindow({ show: false });
  1151. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1152. const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))');
  1153. expect(ok).to.be.false();
  1154. expect(err).to.equal('Not supported');
  1155. });
  1156. });
  1157. describe('window.opener access', () => {
  1158. const scheme = 'app';
  1159. const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
  1160. const httpUrl1 = `${scheme}://origin1`;
  1161. const httpUrl2 = `${scheme}://origin2`;
  1162. const fileBlank = `file://${fixturesPath}/pages/blank.html`;
  1163. const httpBlank = `${scheme}://origin1/blank`;
  1164. const table = [
  1165. { parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false },
  1166. { parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false },
  1167. // {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open()
  1168. // {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open()
  1169. // NB. this is different from Chrome's behavior, which isolates file: urls from each other
  1170. { parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true },
  1171. { parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true },
  1172. { parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true },
  1173. { parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true },
  1174. { parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false },
  1175. { parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false }
  1176. ];
  1177. const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
  1178. before(() => {
  1179. protocol.registerFileProtocol(scheme, (request, callback) => {
  1180. if (request.url.includes('blank')) {
  1181. callback(`${fixturesPath}/pages/blank.html`);
  1182. } else {
  1183. callback(`${fixturesPath}/pages/window-opener-location.html`);
  1184. }
  1185. });
  1186. });
  1187. after(() => {
  1188. protocol.unregisterProtocol(scheme);
  1189. });
  1190. afterEach(closeAllWindows);
  1191. describe('when opened from main window', () => {
  1192. for (const { parent, child, nodeIntegration, openerAccessible } of table) {
  1193. for (const sandboxPopup of [false, true]) {
  1194. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  1195. it(description, async () => {
  1196. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1197. w.webContents.setWindowOpenHandler(() => ({
  1198. action: 'allow',
  1199. overrideBrowserWindowOptions: {
  1200. webPreferences: {
  1201. sandbox: sandboxPopup
  1202. }
  1203. }
  1204. }));
  1205. await w.loadURL(parent);
  1206. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
  1207. window.addEventListener('message', function f(e) {
  1208. resolve(e.data)
  1209. })
  1210. window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
  1211. })`);
  1212. if (openerAccessible) {
  1213. expect(childOpenerLocation).to.be.a('string');
  1214. } else {
  1215. expect(childOpenerLocation).to.be.null();
  1216. }
  1217. });
  1218. }
  1219. }
  1220. });
  1221. describe('when opened from <webview>', () => {
  1222. for (const { parent, child, nodeIntegration, openerAccessible } of table) {
  1223. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  1224. it(description, async () => {
  1225. // This test involves three contexts:
  1226. // 1. The root BrowserWindow in which the test is run,
  1227. // 2. A <webview> belonging to the root window,
  1228. // 3. A window opened by calling window.open() from within the <webview>.
  1229. // We are testing whether context (3) can access context (2) under various conditions.
  1230. // This is context (1), the base window for the test.
  1231. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
  1232. await w.loadURL('about:blank');
  1233. const parentCode = `new Promise((resolve) => {
  1234. // This is context (3), a child window of the WebView.
  1235. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes")
  1236. window.addEventListener("message", e => {
  1237. resolve(e.data)
  1238. })
  1239. })`;
  1240. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  1241. // This is context (2), a WebView which will call window.open()
  1242. const webview = new WebView()
  1243. webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
  1244. webview.setAttribute('webpreferences', 'contextIsolation=no')
  1245. webview.setAttribute('allowpopups', 'on')
  1246. webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
  1247. webview.addEventListener('dom-ready', async () => {
  1248. webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
  1249. })
  1250. document.body.appendChild(webview)
  1251. })`);
  1252. if (openerAccessible) {
  1253. expect(childOpenerLocation).to.be.a('string');
  1254. } else {
  1255. expect(childOpenerLocation).to.be.null();
  1256. }
  1257. });
  1258. }
  1259. });
  1260. });
  1261. describe('storage', () => {
  1262. describe('custom non standard schemes', () => {
  1263. const protocolName = 'storage';
  1264. let contents: WebContents;
  1265. before(() => {
  1266. protocol.registerFileProtocol(protocolName, (request, callback) => {
  1267. const parsedUrl = url.parse(request.url);
  1268. let filename;
  1269. switch (parsedUrl.pathname) {
  1270. case '/localStorage' : filename = 'local_storage.html'; break;
  1271. case '/sessionStorage' : filename = 'session_storage.html'; break;
  1272. case '/WebSQL' : filename = 'web_sql.html'; break;
  1273. case '/indexedDB' : filename = 'indexed_db.html'; break;
  1274. case '/cookie' : filename = 'cookie.html'; break;
  1275. default : filename = '';
  1276. }
  1277. callback({ path: `${fixturesPath}/pages/storage/${filename}` });
  1278. });
  1279. });
  1280. after(() => {
  1281. protocol.unregisterProtocol(protocolName);
  1282. });
  1283. beforeEach(() => {
  1284. contents = (webContents as any).create({
  1285. nodeIntegration: true,
  1286. contextIsolation: false
  1287. });
  1288. });
  1289. afterEach(() => {
  1290. (contents as any).destroy();
  1291. contents = null as any;
  1292. });
  1293. it('cannot access localStorage', async () => {
  1294. const response = emittedOnce(ipcMain, 'local-storage-response');
  1295. contents.loadURL(protocolName + '://host/localStorage');
  1296. const [, error] = await response;
  1297. expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.');
  1298. });
  1299. it('cannot access sessionStorage', async () => {
  1300. const response = emittedOnce(ipcMain, 'session-storage-response');
  1301. contents.loadURL(`${protocolName}://host/sessionStorage`);
  1302. const [, error] = await response;
  1303. expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.');
  1304. });
  1305. it('cannot access WebSQL database', async () => {
  1306. const response = emittedOnce(ipcMain, 'web-sql-response');
  1307. contents.loadURL(`${protocolName}://host/WebSQL`);
  1308. const [, error] = await response;
  1309. expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.');
  1310. });
  1311. it('cannot access indexedDB', async () => {
  1312. const response = emittedOnce(ipcMain, 'indexed-db-response');
  1313. contents.loadURL(`${protocolName}://host/indexedDB`);
  1314. const [, error] = await response;
  1315. expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.');
  1316. });
  1317. it('cannot access cookie', async () => {
  1318. const response = emittedOnce(ipcMain, 'cookie-response');
  1319. contents.loadURL(`${protocolName}://host/cookie`);
  1320. const [, error] = await response;
  1321. expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.');
  1322. });
  1323. });
  1324. describe('can be accessed', () => {
  1325. let server: http.Server;
  1326. let serverUrl: string;
  1327. let serverCrossSiteUrl: string;
  1328. before((done) => {
  1329. server = http.createServer((req, res) => {
  1330. const respond = () => {
  1331. if (req.url === '/redirect-cross-site') {
  1332. res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
  1333. res.statusCode = 302;
  1334. res.end();
  1335. } else if (req.url === '/redirected') {
  1336. res.end('<html><script>window.localStorage</script></html>');
  1337. } else {
  1338. res.end();
  1339. }
  1340. };
  1341. setTimeout(respond, 0);
  1342. });
  1343. server.listen(0, '127.0.0.1', () => {
  1344. serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  1345. serverCrossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`;
  1346. done();
  1347. });
  1348. });
  1349. after(() => {
  1350. server.close();
  1351. server = null as any;
  1352. });
  1353. afterEach(closeAllWindows);
  1354. const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
  1355. it(testTitle, async () => {
  1356. const w = new BrowserWindow({
  1357. show: false,
  1358. ...extraPreferences
  1359. });
  1360. let redirected = false;
  1361. w.webContents.on('crashed', () => {
  1362. expect.fail('renderer crashed / was killed');
  1363. });
  1364. w.webContents.on('did-redirect-navigation', (event, url) => {
  1365. expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
  1366. redirected = true;
  1367. });
  1368. await w.loadURL(`${serverUrl}/redirect-cross-site`);
  1369. expect(redirected).to.be.true('didnt redirect');
  1370. });
  1371. };
  1372. testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
  1373. testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
  1374. });
  1375. describe('enableWebSQL webpreference', () => {
  1376. const origin = `${standardScheme}://fake-host`;
  1377. const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
  1378. const sqlPartition = 'web-sql-preference-test';
  1379. const sqlSession = session.fromPartition(sqlPartition);
  1380. const securityError = 'An attempt was made to break through the security policy of the user agent.';
  1381. let contents: WebContents, w: BrowserWindow;
  1382. before(() => {
  1383. sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
  1384. callback({ path: filePath });
  1385. });
  1386. });
  1387. after(() => {
  1388. sqlSession.protocol.unregisterProtocol(standardScheme);
  1389. });
  1390. afterEach(async () => {
  1391. if (contents) {
  1392. (contents as any).destroy();
  1393. contents = null as any;
  1394. }
  1395. await closeAllWindows();
  1396. (w as any) = null;
  1397. });
  1398. it('default value allows websql', async () => {
  1399. contents = (webContents as any).create({
  1400. session: sqlSession,
  1401. nodeIntegration: true,
  1402. contextIsolation: false
  1403. });
  1404. contents.loadURL(origin);
  1405. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1406. expect(error).to.be.null();
  1407. });
  1408. it('when set to false can disallow websql', async () => {
  1409. contents = (webContents as any).create({
  1410. session: sqlSession,
  1411. nodeIntegration: true,
  1412. enableWebSQL: false,
  1413. contextIsolation: false
  1414. });
  1415. contents.loadURL(origin);
  1416. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1417. expect(error).to.equal(securityError);
  1418. });
  1419. it('when set to false does not disable indexedDB', async () => {
  1420. contents = (webContents as any).create({
  1421. session: sqlSession,
  1422. nodeIntegration: true,
  1423. enableWebSQL: false,
  1424. contextIsolation: false
  1425. });
  1426. contents.loadURL(origin);
  1427. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1428. expect(error).to.equal(securityError);
  1429. const dbName = 'random';
  1430. const result = await contents.executeJavaScript(`
  1431. new Promise((resolve, reject) => {
  1432. try {
  1433. let req = window.indexedDB.open('${dbName}');
  1434. req.onsuccess = (event) => {
  1435. let db = req.result;
  1436. resolve(db.name);
  1437. }
  1438. req.onerror = (event) => { resolve(event.target.code); }
  1439. } catch (e) {
  1440. resolve(e.message);
  1441. }
  1442. });
  1443. `);
  1444. expect(result).to.equal(dbName);
  1445. });
  1446. it('child webContents can override when the embedder has allowed websql', async () => {
  1447. w = new BrowserWindow({
  1448. show: false,
  1449. webPreferences: {
  1450. nodeIntegration: true,
  1451. webviewTag: true,
  1452. session: sqlSession,
  1453. contextIsolation: false
  1454. }
  1455. });
  1456. w.webContents.loadURL(origin);
  1457. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1458. expect(error).to.be.null();
  1459. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1460. await w.webContents.executeJavaScript(`
  1461. new Promise((resolve, reject) => {
  1462. const webview = new WebView();
  1463. webview.setAttribute('src', '${origin}');
  1464. webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no');
  1465. webview.setAttribute('partition', '${sqlPartition}');
  1466. webview.setAttribute('nodeIntegration', 'on');
  1467. document.body.appendChild(webview);
  1468. webview.addEventListener('dom-ready', () => resolve());
  1469. });
  1470. `);
  1471. const [, childError] = await webviewResult;
  1472. expect(childError).to.equal(securityError);
  1473. });
  1474. it('child webContents cannot override when the embedder has disallowed websql', async () => {
  1475. w = new BrowserWindow({
  1476. show: false,
  1477. webPreferences: {
  1478. nodeIntegration: true,
  1479. enableWebSQL: false,
  1480. webviewTag: true,
  1481. session: sqlSession,
  1482. contextIsolation: false
  1483. }
  1484. });
  1485. w.webContents.loadURL('data:text/html,<html></html>');
  1486. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1487. await w.webContents.executeJavaScript(`
  1488. new Promise((resolve, reject) => {
  1489. const webview = new WebView();
  1490. webview.setAttribute('src', '${origin}');
  1491. webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
  1492. webview.setAttribute('partition', '${sqlPartition}');
  1493. webview.setAttribute('nodeIntegration', 'on');
  1494. document.body.appendChild(webview);
  1495. webview.addEventListener('dom-ready', () => resolve());
  1496. });
  1497. `);
  1498. const [, childError] = await webviewResult;
  1499. expect(childError).to.equal(securityError);
  1500. });
  1501. it('child webContents can use websql when the embedder has allowed websql', async () => {
  1502. w = new BrowserWindow({
  1503. show: false,
  1504. webPreferences: {
  1505. nodeIntegration: true,
  1506. webviewTag: true,
  1507. session: sqlSession,
  1508. contextIsolation: false
  1509. }
  1510. });
  1511. w.webContents.loadURL(origin);
  1512. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1513. expect(error).to.be.null();
  1514. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1515. await w.webContents.executeJavaScript(`
  1516. new Promise((resolve, reject) => {
  1517. const webview = new WebView();
  1518. webview.setAttribute('src', '${origin}');
  1519. webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
  1520. webview.setAttribute('partition', '${sqlPartition}');
  1521. webview.setAttribute('nodeIntegration', 'on');
  1522. document.body.appendChild(webview);
  1523. webview.addEventListener('dom-ready', () => resolve());
  1524. });
  1525. `);
  1526. const [, childError] = await webviewResult;
  1527. expect(childError).to.be.null();
  1528. });
  1529. });
  1530. describe('DOM storage quota increase', () => {
  1531. ['localStorage', 'sessionStorage'].forEach((storageName) => {
  1532. it(`allows saving at least 40MiB in ${storageName}`, async () => {
  1533. const w = new BrowserWindow({ show: false });
  1534. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1535. // Although JavaScript strings use UTF-16, the underlying
  1536. // storage provider may encode strings differently, muddling the
  1537. // translation between character and byte counts. However,
  1538. // a string of 40 * 2^20 characters will require at least 40MiB
  1539. // and presumably no more than 80MiB, a size guaranteed to
  1540. // to exceed the original 10MiB quota yet stay within the
  1541. // new 100MiB quota.
  1542. // Note that both the key name and value affect the total size.
  1543. const testKeyName = '_electronDOMStorageQuotaIncreasedTest';
  1544. const length = 40 * Math.pow(2, 20) - testKeyName.length;
  1545. await w.webContents.executeJavaScript(`
  1546. ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
  1547. `);
  1548. // Wait at least one turn of the event loop to help avoid false positives
  1549. // Although not entirely necessary, the previous version of this test case
  1550. // failed to detect a real problem (perhaps related to DOM storage data caching)
  1551. // wherein calling `getItem` immediately after `setItem` would appear to work
  1552. // but then later (e.g. next tick) it would not.
  1553. await delay(1);
  1554. try {
  1555. const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`);
  1556. expect(storedLength).to.equal(length);
  1557. } finally {
  1558. await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
  1559. }
  1560. });
  1561. it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => {
  1562. const w = new BrowserWindow({ show: false });
  1563. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1564. await expect((async () => {
  1565. const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest';
  1566. const length = 128 * Math.pow(2, 20) - testKeyName.length;
  1567. try {
  1568. await w.webContents.executeJavaScript(`
  1569. ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
  1570. `);
  1571. } finally {
  1572. await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
  1573. }
  1574. })()).to.eventually.be.rejected();
  1575. });
  1576. });
  1577. });
  1578. describe('persistent storage', () => {
  1579. it('can be requested', async () => {
  1580. const w = new BrowserWindow({ show: false });
  1581. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1582. const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => {
  1583. navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve);
  1584. })`);
  1585. expect(grantedBytes).to.equal(1048576);
  1586. });
  1587. });
  1588. });
  1589. ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
  1590. const pdfSource = url.format({
  1591. pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'),
  1592. protocol: 'file',
  1593. slashes: true
  1594. });
  1595. it('successfully loads a PDF file', async () => {
  1596. const w = new BrowserWindow({ show: false });
  1597. w.loadURL(pdfSource);
  1598. await emittedOnce(w.webContents, 'did-finish-load');
  1599. });
  1600. it('opens when loading a pdf resource as top level navigation', async () => {
  1601. const w = new BrowserWindow({ show: false });
  1602. w.loadURL(pdfSource);
  1603. const [, contents] = await emittedOnce(app, 'web-contents-created');
  1604. await emittedOnce(contents, 'did-navigate');
  1605. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1606. });
  1607. it('opens when loading a pdf resource in a iframe', async () => {
  1608. const w = new BrowserWindow({ show: false });
  1609. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
  1610. const [, contents] = await emittedOnce(app, 'web-contents-created');
  1611. await emittedOnce(contents, 'did-navigate');
  1612. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1613. });
  1614. });
  1615. describe('window.history', () => {
  1616. describe('window.history.pushState', () => {
  1617. it('should push state after calling history.pushState() from the same url', async () => {
  1618. const w = new BrowserWindow({ show: false });
  1619. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1620. // History should have current page by now.
  1621. expect((w.webContents as any).length()).to.equal(1);
  1622. const waitCommit = emittedOnce(w.webContents, 'navigation-entry-committed');
  1623. w.webContents.executeJavaScript('window.history.pushState({}, "")');
  1624. await waitCommit;
  1625. // Initial page + pushed state.
  1626. expect((w.webContents as any).length()).to.equal(2);
  1627. });
  1628. });
  1629. describe('window.history.back', () => {
  1630. it('should not allow sandboxed iframe to modify main frame state', async () => {
  1631. const w = new BrowserWindow({ show: false });
  1632. w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>');
  1633. await Promise.all([
  1634. emittedOnce(w.webContents, 'navigation-entry-committed'),
  1635. emittedOnce(w.webContents, 'did-frame-navigate'),
  1636. emittedOnce(w.webContents, 'did-navigate')
  1637. ]);
  1638. w.webContents.executeJavaScript('window.history.pushState(1, "")');
  1639. await Promise.all([
  1640. emittedOnce(w.webContents, 'navigation-entry-committed'),
  1641. emittedOnce(w.webContents, 'did-navigate-in-page')
  1642. ]);
  1643. (w.webContents as any).once('navigation-entry-committed', () => {
  1644. expect.fail('Unexpected navigation-entry-committed');
  1645. });
  1646. w.webContents.once('did-navigate-in-page', () => {
  1647. expect.fail('Unexpected did-navigate-in-page');
  1648. });
  1649. await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()');
  1650. expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1);
  1651. expect((w.webContents as any).getActiveIndex()).to.equal(1);
  1652. });
  1653. });
  1654. });
  1655. describe('chrome://media-internals', () => {
  1656. it('loads the page successfully', async () => {
  1657. const w = new BrowserWindow({ show: false });
  1658. w.loadURL('chrome://media-internals');
  1659. const pageExists = await w.webContents.executeJavaScript(
  1660. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1661. );
  1662. expect(pageExists).to.be.true();
  1663. });
  1664. });
  1665. describe('chrome://webrtc-internals', () => {
  1666. it('loads the page successfully', async () => {
  1667. const w = new BrowserWindow({ show: false });
  1668. w.loadURL('chrome://webrtc-internals');
  1669. const pageExists = await w.webContents.executeJavaScript(
  1670. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1671. );
  1672. expect(pageExists).to.be.true();
  1673. });
  1674. });
  1675. describe('document.hasFocus', () => {
  1676. it('has correct value when multiple windows are opened', async () => {
  1677. const w1 = new BrowserWindow({ show: true });
  1678. const w2 = new BrowserWindow({ show: true });
  1679. const w3 = new BrowserWindow({ show: false });
  1680. await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1681. await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1682. await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1683. expect(webContents.getFocusedWebContents().id).to.equal(w2.webContents.id);
  1684. let focus = false;
  1685. focus = await w1.webContents.executeJavaScript(
  1686. 'document.hasFocus()'
  1687. );
  1688. expect(focus).to.be.false();
  1689. focus = await w2.webContents.executeJavaScript(
  1690. 'document.hasFocus()'
  1691. );
  1692. expect(focus).to.be.true();
  1693. focus = await w3.webContents.executeJavaScript(
  1694. 'document.hasFocus()'
  1695. );
  1696. expect(focus).to.be.false();
  1697. });
  1698. });
  1699. describe('navigator.userAgentData', () => {
  1700. // These tests are done on an http server because navigator.userAgentData
  1701. // requires a secure context.
  1702. let server: http.Server;
  1703. let serverUrl: string;
  1704. before(async () => {
  1705. server = http.createServer((req, res) => {
  1706. res.setHeader('Content-Type', 'text/html');
  1707. res.end('');
  1708. });
  1709. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1710. serverUrl = `http://localhost:${(server.address() as any).port}`;
  1711. });
  1712. after(() => {
  1713. server.close();
  1714. });
  1715. describe('is not empty', () => {
  1716. it('by default', async () => {
  1717. const w = new BrowserWindow({ show: false });
  1718. await w.loadURL(serverUrl);
  1719. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1720. expect(platform).not.to.be.empty();
  1721. });
  1722. it('when there is a session-wide UA override', async () => {
  1723. const ses = session.fromPartition(`${Math.random()}`);
  1724. ses.setUserAgent('foobar');
  1725. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  1726. await w.loadURL(serverUrl);
  1727. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1728. expect(platform).not.to.be.empty();
  1729. });
  1730. it('when there is a WebContents-specific UA override', async () => {
  1731. const w = new BrowserWindow({ show: false });
  1732. w.webContents.setUserAgent('foo');
  1733. await w.loadURL(serverUrl);
  1734. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1735. expect(platform).not.to.be.empty();
  1736. });
  1737. it('when there is a WebContents-specific UA override at load time', async () => {
  1738. const w = new BrowserWindow({ show: false });
  1739. await w.loadURL(serverUrl, {
  1740. userAgent: 'foo'
  1741. });
  1742. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1743. expect(platform).not.to.be.empty();
  1744. });
  1745. });
  1746. describe('brand list', () => {
  1747. it('contains chromium', async () => {
  1748. const w = new BrowserWindow({ show: false });
  1749. await w.loadURL(serverUrl);
  1750. const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands');
  1751. expect(brands.map((b: any) => b.brand)).to.include('Chromium');
  1752. });
  1753. });
  1754. });
  1755. describe('Badging API', () => {
  1756. it('does not crash', async () => {
  1757. const w = new BrowserWindow({ show: false });
  1758. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1759. await w.webContents.executeJavaScript('navigator.setAppBadge(42)');
  1760. await w.webContents.executeJavaScript('navigator.setAppBadge()');
  1761. await w.webContents.executeJavaScript('navigator.clearAppBadge()');
  1762. });
  1763. });
  1764. describe('navigator.webkitGetUserMedia', () => {
  1765. it('calls its callbacks', async () => {
  1766. const w = new BrowserWindow({ show: false });
  1767. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1768. await w.webContents.executeJavaScript(`new Promise((resolve) => {
  1769. navigator.webkitGetUserMedia({
  1770. audio: true,
  1771. video: false
  1772. }, () => resolve(),
  1773. () => resolve());
  1774. })`);
  1775. });
  1776. });
  1777. describe('navigator.language', () => {
  1778. it('should not be empty', async () => {
  1779. const w = new BrowserWindow({ show: false });
  1780. await w.loadURL('about:blank');
  1781. expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal('');
  1782. });
  1783. });
  1784. describe('heap snapshot', () => {
  1785. it('does not crash', async () => {
  1786. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1787. w.loadURL('about:blank');
  1788. await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()');
  1789. });
  1790. });
  1791. ifdescribe(process.platform !== 'win32' && process.platform !== 'linux')('webgl', () => {
  1792. it('can be gotten as context in canvas', async () => {
  1793. const w = new BrowserWindow({ show: false });
  1794. w.loadURL('about:blank');
  1795. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1796. const canWebglContextBeCreated = await w.webContents.executeJavaScript(`
  1797. document.createElement('canvas').getContext('webgl') != null;
  1798. `);
  1799. expect(canWebglContextBeCreated).to.be.true();
  1800. });
  1801. });
  1802. describe('iframe', () => {
  1803. it('does not have node integration', async () => {
  1804. const w = new BrowserWindow({ show: false });
  1805. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1806. const result = await w.webContents.executeJavaScript(`
  1807. const iframe = document.createElement('iframe')
  1808. iframe.src = './set-global.html';
  1809. document.body.appendChild(iframe);
  1810. new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test))
  1811. `);
  1812. expect(result).to.equal('undefined undefined undefined');
  1813. });
  1814. });
  1815. describe('websockets', () => {
  1816. it('has user agent', async () => {
  1817. const server = http.createServer();
  1818. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1819. const port = (server.address() as AddressInfo).port;
  1820. const wss = new ws.Server({ server: server });
  1821. const finished = new Promise<string | undefined>((resolve, reject) => {
  1822. wss.on('error', reject);
  1823. wss.on('connection', (ws, upgradeReq) => {
  1824. resolve(upgradeReq.headers['user-agent']);
  1825. });
  1826. });
  1827. const w = new BrowserWindow({ show: false });
  1828. w.loadURL('about:blank');
  1829. w.webContents.executeJavaScript(`
  1830. new WebSocket('ws://127.0.0.1:${port}');
  1831. `);
  1832. expect(await finished).to.include('Electron');
  1833. });
  1834. });
  1835. describe('fetch', () => {
  1836. it('does not crash', async () => {
  1837. const server = http.createServer((req, res) => {
  1838. res.end('test');
  1839. });
  1840. defer(() => server.close());
  1841. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1842. const port = (server.address() as AddressInfo).port;
  1843. const w = new BrowserWindow({ show: false });
  1844. w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1845. const x = await w.webContents.executeJavaScript(`
  1846. fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader())
  1847. .then((reader) => {
  1848. return reader.read().then((r) => {
  1849. reader.cancel();
  1850. return r.value;
  1851. });
  1852. })
  1853. `);
  1854. expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116]));
  1855. });
  1856. });
  1857. describe('Promise', () => {
  1858. before(() => {
  1859. ipcMain.handle('ping', (e, arg) => arg);
  1860. });
  1861. after(() => {
  1862. ipcMain.removeHandler('ping');
  1863. });
  1864. itremote('resolves correctly in Node.js calls', async () => {
  1865. await new Promise<void>((resolve, reject) => {
  1866. class XElement extends HTMLElement {}
  1867. customElements.define('x-element', XElement);
  1868. setImmediate(() => {
  1869. let called = false;
  1870. Promise.resolve().then(() => {
  1871. if (called) resolve();
  1872. else reject(new Error('wrong sequence'));
  1873. });
  1874. document.createElement('x-element');
  1875. called = true;
  1876. });
  1877. });
  1878. });
  1879. itremote('resolves correctly in Electron calls', async () => {
  1880. await new Promise<void>((resolve, reject) => {
  1881. class YElement extends HTMLElement {}
  1882. customElements.define('y-element', YElement);
  1883. require('electron').ipcRenderer.invoke('ping').then(() => {
  1884. let called = false;
  1885. Promise.resolve().then(() => {
  1886. if (called) resolve();
  1887. else reject(new Error('wrong sequence'));
  1888. });
  1889. document.createElement('y-element');
  1890. called = true;
  1891. });
  1892. });
  1893. });
  1894. });
  1895. describe('synchronous prompts', () => {
  1896. describe('window.alert(message, title)', () => {
  1897. itremote('throws an exception when the arguments cannot be converted to strings', () => {
  1898. expect(() => {
  1899. window.alert({ toString: null });
  1900. }).to.throw('Cannot convert object to primitive value');
  1901. });
  1902. });
  1903. describe('window.confirm(message, title)', () => {
  1904. itremote('throws an exception when the arguments cannot be converted to strings', () => {
  1905. expect(() => {
  1906. (window.confirm as any)({ toString: null }, 'title');
  1907. }).to.throw('Cannot convert object to primitive value');
  1908. });
  1909. });
  1910. });
  1911. describe('window.history', () => {
  1912. describe('window.history.go(offset)', () => {
  1913. itremote('throws an exception when the argument cannot be converted to a string', () => {
  1914. expect(() => {
  1915. (window.history.go as any)({ toString: null });
  1916. }).to.throw('Cannot convert object to primitive value');
  1917. });
  1918. });
  1919. });
  1920. describe('console functions', () => {
  1921. itremote('should exist', () => {
  1922. expect(console.log, 'log').to.be.a('function');
  1923. expect(console.error, 'error').to.be.a('function');
  1924. expect(console.warn, 'warn').to.be.a('function');
  1925. expect(console.info, 'info').to.be.a('function');
  1926. expect(console.debug, 'debug').to.be.a('function');
  1927. expect(console.trace, 'trace').to.be.a('function');
  1928. expect(console.time, 'time').to.be.a('function');
  1929. expect(console.timeEnd, 'timeEnd').to.be.a('function');
  1930. });
  1931. });
  1932. ifdescribe(features.isTtsEnabled())('SpeechSynthesis', () => {
  1933. before(function () {
  1934. // TODO(nornagon): this is broken on CI, it triggers:
  1935. // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will
  1936. // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side
  1937. // (null text in SpeechSynthesisUtterance struct).
  1938. this.skip();
  1939. });
  1940. itremote('should emit lifecycle events', async () => {
  1941. const sentence = `long sentence which will take at least a few seconds to
  1942. utter so that it's possible to pause and resume before the end`;
  1943. const utter = new SpeechSynthesisUtterance(sentence);
  1944. // Create a dummy utterance so that speech synthesis state
  1945. // is initialized for later calls.
  1946. speechSynthesis.speak(new SpeechSynthesisUtterance());
  1947. speechSynthesis.cancel();
  1948. speechSynthesis.speak(utter);
  1949. // paused state after speak()
  1950. expect(speechSynthesis.paused).to.be.false();
  1951. await new Promise((resolve) => { utter.onstart = resolve; });
  1952. // paused state after start event
  1953. expect(speechSynthesis.paused).to.be.false();
  1954. speechSynthesis.pause();
  1955. // paused state changes async, right before the pause event
  1956. expect(speechSynthesis.paused).to.be.false();
  1957. await new Promise((resolve) => { utter.onpause = resolve; });
  1958. expect(speechSynthesis.paused).to.be.true();
  1959. speechSynthesis.resume();
  1960. await new Promise((resolve) => { utter.onresume = resolve; });
  1961. // paused state after resume event
  1962. expect(speechSynthesis.paused).to.be.false();
  1963. await new Promise((resolve) => { utter.onend = resolve; });
  1964. });
  1965. });
  1966. });
  1967. describe('font fallback', () => {
  1968. async function getRenderedFonts (html: string) {
  1969. const w = new BrowserWindow({ show: false });
  1970. try {
  1971. await w.loadURL(`data:text/html,${html}`);
  1972. w.webContents.debugger.attach();
  1973. const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
  1974. const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
  1975. await sendCommand('CSS.enable');
  1976. const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
  1977. return fonts;
  1978. } finally {
  1979. w.close();
  1980. }
  1981. }
  1982. it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
  1983. const html = '<body style="font-family: sans-serif">test</body>';
  1984. const fonts = await getRenderedFonts(html);
  1985. expect(fonts).to.be.an('array');
  1986. expect(fonts).to.have.length(1);
  1987. if (process.platform === 'win32') {
  1988. expect(fonts[0].familyName).to.equal('Arial');
  1989. } else if (process.platform === 'darwin') {
  1990. expect(fonts[0].familyName).to.equal('Helvetica');
  1991. } else if (process.platform === 'linux') {
  1992. expect(fonts[0].familyName).to.equal('DejaVu Sans');
  1993. } // I think this depends on the distro? We don't specify a default.
  1994. });
  1995. ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
  1996. const html = `
  1997. <html lang="ja-JP">
  1998. <head>
  1999. <meta charset="utf-8" />
  2000. </head>
  2001. <body style="font-family: sans-serif">test 智史</body>
  2002. </html>
  2003. `;
  2004. const fonts = await getRenderedFonts(html);
  2005. expect(fonts).to.be.an('array');
  2006. expect(fonts).to.have.length(1);
  2007. 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'); }
  2008. });
  2009. });
  2010. describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
  2011. const fullscreenChildHtml = promisify(fs.readFile)(
  2012. path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
  2013. );
  2014. let w: BrowserWindow, server: http.Server;
  2015. before(() => {
  2016. server = http.createServer(async (_req, res) => {
  2017. res.writeHead(200, { 'Content-Type': 'text/html' });
  2018. res.write(await fullscreenChildHtml);
  2019. res.end();
  2020. });
  2021. server.listen(8989, '127.0.0.1');
  2022. });
  2023. beforeEach(() => {
  2024. w = new BrowserWindow({
  2025. show: true,
  2026. fullscreen: true,
  2027. webPreferences: {
  2028. nodeIntegration: true,
  2029. nodeIntegrationInSubFrames: true,
  2030. contextIsolation: false
  2031. }
  2032. });
  2033. });
  2034. afterEach(async () => {
  2035. await closeAllWindows();
  2036. (w as any) = null;
  2037. server.close();
  2038. });
  2039. ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => {
  2040. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  2041. const html =
  2042. '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>';
  2043. w.loadURL(`data:text/html,${html}`);
  2044. await fullscreenChange;
  2045. const fullscreenWidth = await w.webContents.executeJavaScript(
  2046. "document.querySelector('iframe').offsetWidth"
  2047. );
  2048. expect(fullscreenWidth > 0).to.be.true();
  2049. await w.webContents.executeJavaScript(
  2050. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  2051. );
  2052. await delay(500);
  2053. const width = await w.webContents.executeJavaScript(
  2054. "document.querySelector('iframe').offsetWidth"
  2055. );
  2056. expect(width).to.equal(0);
  2057. });
  2058. ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => {
  2059. await emittedOnce(w, 'enter-full-screen');
  2060. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  2061. const html =
  2062. '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>';
  2063. w.loadURL(`data:text/html,${html}`);
  2064. await fullscreenChange;
  2065. const fullscreenWidth = await w.webContents.executeJavaScript(
  2066. "document.querySelector('iframe').offsetWidth"
  2067. );
  2068. expect(fullscreenWidth > 0).to.be.true();
  2069. await w.webContents.executeJavaScript(
  2070. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  2071. );
  2072. await emittedOnce(w.webContents, 'leave-html-full-screen');
  2073. const width = await w.webContents.executeJavaScript(
  2074. "document.querySelector('iframe').offsetWidth"
  2075. );
  2076. expect(width).to.equal(0);
  2077. w.setFullScreen(false);
  2078. await emittedOnce(w, 'leave-full-screen');
  2079. });
  2080. // TODO(jkleinsc) fix this flaky test on WOA
  2081. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => {
  2082. if (process.platform === 'darwin') await emittedOnce(w, 'enter-full-screen');
  2083. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  2084. w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
  2085. await fullscreenChange;
  2086. const fullscreenWidth = await w.webContents.executeJavaScript(
  2087. "document.querySelector('iframe').offsetWidth"
  2088. );
  2089. expect(fullscreenWidth > 0).to.true();
  2090. await w.webContents.executeJavaScript('document.exitFullscreen()');
  2091. const width = await w.webContents.executeJavaScript(
  2092. "document.querySelector('iframe').offsetWidth"
  2093. );
  2094. expect(width).to.equal(0);
  2095. });
  2096. });
  2097. describe('navigator.serial', () => {
  2098. let w: BrowserWindow;
  2099. before(async () => {
  2100. w = new BrowserWindow({
  2101. show: false
  2102. });
  2103. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2104. });
  2105. const getPorts: any = () => {
  2106. return w.webContents.executeJavaScript(`
  2107. navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
  2108. `, true);
  2109. };
  2110. after(closeAllWindows);
  2111. afterEach(() => {
  2112. session.defaultSession.setPermissionCheckHandler(null);
  2113. session.defaultSession.removeAllListeners('select-serial-port');
  2114. });
  2115. it('does not return a port if select-serial-port event is not defined', async () => {
  2116. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2117. const port = await getPorts();
  2118. expect(port).to.equal('NotFoundError: No port selected by the user.');
  2119. });
  2120. it('does not return a port when permission denied', async () => {
  2121. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2122. callback(portList[0].portId);
  2123. });
  2124. session.defaultSession.setPermissionCheckHandler(() => false);
  2125. const port = await getPorts();
  2126. expect(port).to.equal('NotFoundError: No port selected by the user.');
  2127. });
  2128. it('does not crash when select-serial-port is called with an invalid port', async () => {
  2129. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2130. callback('i-do-not-exist');
  2131. });
  2132. const port = await getPorts();
  2133. expect(port).to.equal('NotFoundError: No port selected by the user.');
  2134. });
  2135. it('returns a port when select-serial-port event is defined', async () => {
  2136. let havePorts = false;
  2137. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2138. if (portList.length > 0) {
  2139. havePorts = true;
  2140. callback(portList[0].portId);
  2141. } else {
  2142. callback('');
  2143. }
  2144. });
  2145. const port = await getPorts();
  2146. if (havePorts) {
  2147. expect(port).to.equal('[object SerialPort]');
  2148. } else {
  2149. expect(port).to.equal('NotFoundError: No port selected by the user.');
  2150. }
  2151. });
  2152. it('navigator.serial.getPorts() returns values', async () => {
  2153. let havePorts = false;
  2154. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2155. if (portList.length > 0) {
  2156. havePorts = true;
  2157. callback(portList[0].portId);
  2158. } else {
  2159. callback('');
  2160. }
  2161. });
  2162. await getPorts();
  2163. if (havePorts) {
  2164. const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
  2165. expect(grantedPorts).to.not.be.empty();
  2166. }
  2167. });
  2168. });
  2169. describe('navigator.clipboard', () => {
  2170. let w: BrowserWindow;
  2171. before(async () => {
  2172. w = new BrowserWindow({
  2173. webPreferences: {
  2174. enableBlinkFeatures: 'Serial'
  2175. }
  2176. });
  2177. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2178. });
  2179. const readClipboard: any = () => {
  2180. return w.webContents.executeJavaScript(`
  2181. navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
  2182. `, true);
  2183. };
  2184. after(closeAllWindows);
  2185. afterEach(() => {
  2186. session.defaultSession.setPermissionRequestHandler(null);
  2187. });
  2188. it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
  2189. const clipboard = await readClipboard();
  2190. expect(clipboard).to.not.equal('Read permission denied.');
  2191. });
  2192. it('returns an error when permission denied', async () => {
  2193. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2194. if (permission === 'clipboard-read') {
  2195. callback(false);
  2196. } else {
  2197. callback(true);
  2198. }
  2199. });
  2200. const clipboard = await readClipboard();
  2201. expect(clipboard).to.equal('Read permission denied.');
  2202. });
  2203. it('returns clipboard contents when permission is granted', async () => {
  2204. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2205. if (permission === 'clipboard-read') {
  2206. callback(true);
  2207. } else {
  2208. callback(false);
  2209. }
  2210. });
  2211. const clipboard = await readClipboard();
  2212. expect(clipboard).to.not.equal('Read permission denied.');
  2213. });
  2214. });
  2215. ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
  2216. let w: BrowserWindow;
  2217. const expectedBadgeCount = 42;
  2218. const fireAppBadgeAction: any = (action: string, value: any) => {
  2219. return w.webContents.executeJavaScript(`
  2220. navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
  2221. };
  2222. // For some reason on macOS changing the badge count doesn't happen right away, so wait
  2223. // until it changes.
  2224. async function waitForBadgeCount (value: number) {
  2225. let badgeCount = app.getBadgeCount();
  2226. while (badgeCount !== value) {
  2227. await new Promise(resolve => setTimeout(resolve, 10));
  2228. badgeCount = app.getBadgeCount();
  2229. }
  2230. return badgeCount;
  2231. }
  2232. describe('in the renderer', () => {
  2233. before(async () => {
  2234. w = new BrowserWindow({
  2235. show: false
  2236. });
  2237. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2238. });
  2239. after(() => {
  2240. app.badgeCount = 0;
  2241. closeAllWindows();
  2242. });
  2243. it('setAppBadge can set a numerical value', async () => {
  2244. const result = await fireAppBadgeAction('set', expectedBadgeCount);
  2245. expect(result).to.equal('success');
  2246. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2247. });
  2248. it('setAppBadge can set an empty(dot) value', async () => {
  2249. const result = await fireAppBadgeAction('set');
  2250. expect(result).to.equal('success');
  2251. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  2252. });
  2253. it('clearAppBadge can clear a value', async () => {
  2254. let result = await fireAppBadgeAction('set', expectedBadgeCount);
  2255. expect(result).to.equal('success');
  2256. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2257. result = await fireAppBadgeAction('clear');
  2258. expect(result).to.equal('success');
  2259. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  2260. });
  2261. });
  2262. describe('in a service worker', () => {
  2263. beforeEach(async () => {
  2264. w = new BrowserWindow({
  2265. show: false,
  2266. webPreferences: {
  2267. nodeIntegration: true,
  2268. partition: 'sw-file-scheme-spec',
  2269. contextIsolation: false
  2270. }
  2271. });
  2272. });
  2273. afterEach(() => {
  2274. app.badgeCount = 0;
  2275. closeAllWindows();
  2276. });
  2277. it('setAppBadge can be called in a ServiceWorker', (done) => {
  2278. w.webContents.on('ipc-message', (event, channel, message) => {
  2279. if (channel === 'reload') {
  2280. w.webContents.reload();
  2281. } else if (channel === 'error') {
  2282. done(message);
  2283. } else if (channel === 'response') {
  2284. expect(message).to.equal('SUCCESS setting app badge');
  2285. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2286. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  2287. storages: ['serviceworkers']
  2288. }).then(() => done());
  2289. }
  2290. });
  2291. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  2292. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
  2293. });
  2294. it('clearAppBadge can be called in a ServiceWorker', (done) => {
  2295. w.webContents.on('ipc-message', (event, channel, message) => {
  2296. if (channel === 'reload') {
  2297. w.webContents.reload();
  2298. } else if (channel === 'setAppBadge') {
  2299. expect(message).to.equal('SUCCESS setting app badge');
  2300. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2301. } else if (channel === 'error') {
  2302. done(message);
  2303. } else if (channel === 'response') {
  2304. expect(message).to.equal('SUCCESS clearing app badge');
  2305. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2306. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  2307. storages: ['serviceworkers']
  2308. }).then(() => done());
  2309. }
  2310. });
  2311. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  2312. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
  2313. });
  2314. });
  2315. });
  2316. describe('navigator.bluetooth', () => {
  2317. let w: BrowserWindow;
  2318. before(async () => {
  2319. w = new BrowserWindow({
  2320. show: false,
  2321. webPreferences: {
  2322. enableBlinkFeatures: 'WebBluetooth'
  2323. }
  2324. });
  2325. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2326. });
  2327. after(closeAllWindows);
  2328. it('can request bluetooth devices', async () => {
  2329. const bluetooth = await w.webContents.executeJavaScript(`
  2330. navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
  2331. expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
  2332. });
  2333. });
  2334. describe('navigator.hid', () => {
  2335. let w: BrowserWindow;
  2336. let server: http.Server;
  2337. let serverUrl: string;
  2338. before(async () => {
  2339. w = new BrowserWindow({
  2340. show: false
  2341. });
  2342. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2343. server = http.createServer((req, res) => {
  2344. res.setHeader('Content-Type', 'text/html');
  2345. res.end('<body>');
  2346. });
  2347. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  2348. serverUrl = `http://localhost:${(server.address() as any).port}`;
  2349. });
  2350. const requestDevices: any = () => {
  2351. return w.webContents.executeJavaScript(`
  2352. navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
  2353. `, true);
  2354. };
  2355. after(() => {
  2356. server.close();
  2357. closeAllWindows();
  2358. });
  2359. afterEach(() => {
  2360. session.defaultSession.setPermissionCheckHandler(null);
  2361. session.defaultSession.setDevicePermissionHandler(null);
  2362. session.defaultSession.removeAllListeners('select-hid-device');
  2363. });
  2364. it('does not return a device if select-hid-device event is not defined', async () => {
  2365. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2366. const device = await requestDevices();
  2367. expect(device).to.equal('');
  2368. });
  2369. it('does not return a device when permission denied', async () => {
  2370. let selectFired = false;
  2371. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2372. selectFired = true;
  2373. callback();
  2374. });
  2375. session.defaultSession.setPermissionCheckHandler(() => false);
  2376. const device = await requestDevices();
  2377. expect(selectFired).to.be.false();
  2378. expect(device).to.equal('');
  2379. });
  2380. it('returns a device when select-hid-device event is defined', async () => {
  2381. let haveDevices = false;
  2382. let selectFired = false;
  2383. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2384. expect(details.frame).to.have.ownProperty('frameTreeNodeId').that.is.a('number');
  2385. selectFired = true;
  2386. if (details.deviceList.length > 0) {
  2387. haveDevices = true;
  2388. callback(details.deviceList[0].deviceId);
  2389. } else {
  2390. callback();
  2391. }
  2392. });
  2393. const device = await requestDevices();
  2394. expect(selectFired).to.be.true();
  2395. if (haveDevices) {
  2396. expect(device).to.contain('[object HIDDevice]');
  2397. } else {
  2398. expect(device).to.equal('');
  2399. }
  2400. if (process.arch === 'arm64' || process.arch === 'arm') {
  2401. // arm CI returns HID devices - this block may need to change if CI hardware changes.
  2402. expect(haveDevices).to.be.true();
  2403. // Verify that navigation will clear device permissions
  2404. const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  2405. expect(grantedDevices).to.not.be.empty();
  2406. w.loadURL(serverUrl);
  2407. const [,,,,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-navigate');
  2408. const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
  2409. expect(frame).to.not.be.empty();
  2410. if (frame) {
  2411. const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
  2412. expect(grantedDevicesOnNewPage).to.be.empty();
  2413. }
  2414. }
  2415. });
  2416. it('returns a device when DevicePermissionHandler is defined', async () => {
  2417. let haveDevices = false;
  2418. let selectFired = false;
  2419. let gotDevicePerms = false;
  2420. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2421. selectFired = true;
  2422. if (details.deviceList.length > 0) {
  2423. const foundDevice = details.deviceList.find((device) => {
  2424. if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
  2425. haveDevices = true;
  2426. return true;
  2427. }
  2428. });
  2429. if (foundDevice) {
  2430. callback(foundDevice.deviceId);
  2431. return;
  2432. }
  2433. }
  2434. callback();
  2435. });
  2436. session.defaultSession.setDevicePermissionHandler(() => {
  2437. gotDevicePerms = true;
  2438. return true;
  2439. });
  2440. await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
  2441. const device = await requestDevices();
  2442. expect(selectFired).to.be.true();
  2443. if (haveDevices) {
  2444. expect(device).to.contain('[object HIDDevice]');
  2445. expect(gotDevicePerms).to.be.true();
  2446. } else {
  2447. expect(device).to.equal('');
  2448. }
  2449. });
  2450. it('excludes a device when a exclusionFilter is specified', async () => {
  2451. const exclusionFilters = <any>[];
  2452. let haveDevices = false;
  2453. let checkForExcludedDevice = false;
  2454. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2455. if (details.deviceList.length > 0) {
  2456. details.deviceList.find((device) => {
  2457. if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
  2458. if (checkForExcludedDevice) {
  2459. const compareDevice = {
  2460. vendorId: device.vendorId,
  2461. productId: device.productId
  2462. };
  2463. expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned');
  2464. } else {
  2465. haveDevices = true;
  2466. exclusionFilters.push({
  2467. vendorId: device.vendorId,
  2468. productId: device.productId
  2469. });
  2470. return true;
  2471. }
  2472. }
  2473. });
  2474. }
  2475. callback();
  2476. });
  2477. await requestDevices();
  2478. if (haveDevices) {
  2479. // We have devices to exclude, so check if exclusionFilters work
  2480. checkForExcludedDevice = true;
  2481. await w.webContents.executeJavaScript(`
  2482. navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString());
  2483. `, true);
  2484. }
  2485. });
  2486. it('supports device.forget()', async () => {
  2487. let deletedDeviceFromEvent;
  2488. let haveDevices = false;
  2489. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2490. if (details.deviceList.length > 0) {
  2491. haveDevices = true;
  2492. callback(details.deviceList[0].deviceId);
  2493. } else {
  2494. callback();
  2495. }
  2496. });
  2497. w.webContents.session.on('hid-device-revoked', (event, details) => {
  2498. deletedDeviceFromEvent = details.device;
  2499. });
  2500. await requestDevices();
  2501. if (haveDevices) {
  2502. const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  2503. if (grantedDevices.length > 0) {
  2504. const deletedDevice = await w.webContents.executeJavaScript(`
  2505. navigator.hid.getDevices().then(devices => {
  2506. devices[0].forget();
  2507. return {
  2508. vendorId: devices[0].vendorId,
  2509. productId: devices[0].productId,
  2510. name: devices[0].productName
  2511. }
  2512. })
  2513. `);
  2514. const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  2515. expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
  2516. if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) {
  2517. expect(deletedDeviceFromEvent).to.include(deletedDevice);
  2518. }
  2519. }
  2520. }
  2521. });
  2522. });