chromium-spec.ts 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775
  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. });
  1630. describe('chrome://media-internals', () => {
  1631. it('loads the page successfully', async () => {
  1632. const w = new BrowserWindow({ show: false });
  1633. w.loadURL('chrome://media-internals');
  1634. const pageExists = await w.webContents.executeJavaScript(
  1635. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1636. );
  1637. expect(pageExists).to.be.true();
  1638. });
  1639. });
  1640. describe('chrome://webrtc-internals', () => {
  1641. it('loads the page successfully', async () => {
  1642. const w = new BrowserWindow({ show: false });
  1643. w.loadURL('chrome://webrtc-internals');
  1644. const pageExists = await w.webContents.executeJavaScript(
  1645. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1646. );
  1647. expect(pageExists).to.be.true();
  1648. });
  1649. });
  1650. describe('document.hasFocus', () => {
  1651. it('has correct value when multiple windows are opened', async () => {
  1652. const w1 = new BrowserWindow({ show: true });
  1653. const w2 = new BrowserWindow({ show: true });
  1654. const w3 = new BrowserWindow({ show: false });
  1655. await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1656. await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1657. await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1658. expect(webContents.getFocusedWebContents().id).to.equal(w2.webContents.id);
  1659. let focus = false;
  1660. focus = await w1.webContents.executeJavaScript(
  1661. 'document.hasFocus()'
  1662. );
  1663. expect(focus).to.be.false();
  1664. focus = await w2.webContents.executeJavaScript(
  1665. 'document.hasFocus()'
  1666. );
  1667. expect(focus).to.be.true();
  1668. focus = await w3.webContents.executeJavaScript(
  1669. 'document.hasFocus()'
  1670. );
  1671. expect(focus).to.be.false();
  1672. });
  1673. });
  1674. describe('navigator.userAgentData', () => {
  1675. // These tests are done on an http server because navigator.userAgentData
  1676. // requires a secure context.
  1677. let server: http.Server;
  1678. let serverUrl: string;
  1679. before(async () => {
  1680. server = http.createServer((req, res) => {
  1681. res.setHeader('Content-Type', 'text/html');
  1682. res.end('');
  1683. });
  1684. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1685. serverUrl = `http://localhost:${(server.address() as any).port}`;
  1686. });
  1687. after(() => {
  1688. server.close();
  1689. });
  1690. describe('is not empty', () => {
  1691. it('by default', async () => {
  1692. const w = new BrowserWindow({ show: false });
  1693. await w.loadURL(serverUrl);
  1694. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1695. expect(platform).not.to.be.empty();
  1696. });
  1697. it('when there is a session-wide UA override', async () => {
  1698. const ses = session.fromPartition(`${Math.random()}`);
  1699. ses.setUserAgent('foobar');
  1700. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  1701. await w.loadURL(serverUrl);
  1702. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1703. expect(platform).not.to.be.empty();
  1704. });
  1705. it('when there is a WebContents-specific UA override', async () => {
  1706. const w = new BrowserWindow({ show: false });
  1707. w.webContents.setUserAgent('foo');
  1708. await w.loadURL(serverUrl);
  1709. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1710. expect(platform).not.to.be.empty();
  1711. });
  1712. it('when there is a WebContents-specific UA override at load time', async () => {
  1713. const w = new BrowserWindow({ show: false });
  1714. await w.loadURL(serverUrl, {
  1715. userAgent: 'foo'
  1716. });
  1717. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1718. expect(platform).not.to.be.empty();
  1719. });
  1720. });
  1721. describe('brand list', () => {
  1722. it('contains chromium', async () => {
  1723. const w = new BrowserWindow({ show: false });
  1724. await w.loadURL(serverUrl);
  1725. const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands');
  1726. expect(brands.map((b: any) => b.brand)).to.include('Chromium');
  1727. });
  1728. });
  1729. });
  1730. describe('Badging API', () => {
  1731. it('does not crash', async () => {
  1732. const w = new BrowserWindow({ show: false });
  1733. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1734. await w.webContents.executeJavaScript('navigator.setAppBadge(42)');
  1735. await w.webContents.executeJavaScript('navigator.setAppBadge()');
  1736. await w.webContents.executeJavaScript('navigator.clearAppBadge()');
  1737. });
  1738. });
  1739. describe('navigator.webkitGetUserMedia', () => {
  1740. it('calls its callbacks', async () => {
  1741. const w = new BrowserWindow({ show: false });
  1742. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1743. await w.webContents.executeJavaScript(`new Promise((resolve) => {
  1744. navigator.webkitGetUserMedia({
  1745. audio: true,
  1746. video: false
  1747. }, () => resolve(),
  1748. () => resolve());
  1749. })`);
  1750. });
  1751. });
  1752. describe('navigator.language', () => {
  1753. it('should not be empty', async () => {
  1754. const w = new BrowserWindow({ show: false });
  1755. await w.loadURL('about:blank');
  1756. expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal('');
  1757. });
  1758. });
  1759. describe('heap snapshot', () => {
  1760. it('does not crash', async () => {
  1761. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1762. w.loadURL('about:blank');
  1763. await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()');
  1764. });
  1765. });
  1766. ifdescribe(process.platform !== 'win32' && process.platform !== 'linux')('webgl', () => {
  1767. it('can be gotten as context in canvas', async () => {
  1768. const w = new BrowserWindow({ show: false });
  1769. w.loadURL('about:blank');
  1770. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1771. const canWebglContextBeCreated = await w.webContents.executeJavaScript(`
  1772. document.createElement('canvas').getContext('webgl') != null;
  1773. `);
  1774. expect(canWebglContextBeCreated).to.be.true();
  1775. });
  1776. });
  1777. describe('iframe', () => {
  1778. it('does not have node integration', async () => {
  1779. const w = new BrowserWindow({ show: false });
  1780. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1781. const result = await w.webContents.executeJavaScript(`
  1782. const iframe = document.createElement('iframe')
  1783. iframe.src = './set-global.html';
  1784. document.body.appendChild(iframe);
  1785. new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test))
  1786. `);
  1787. expect(result).to.equal('undefined undefined undefined');
  1788. });
  1789. });
  1790. describe('websockets', () => {
  1791. it('has user agent', async () => {
  1792. const server = http.createServer();
  1793. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1794. const port = (server.address() as AddressInfo).port;
  1795. const wss = new ws.Server({ server: server });
  1796. const finished = new Promise<string | undefined>((resolve, reject) => {
  1797. wss.on('error', reject);
  1798. wss.on('connection', (ws, upgradeReq) => {
  1799. resolve(upgradeReq.headers['user-agent']);
  1800. });
  1801. });
  1802. const w = new BrowserWindow({ show: false });
  1803. w.loadURL('about:blank');
  1804. w.webContents.executeJavaScript(`
  1805. new WebSocket('ws://127.0.0.1:${port}');
  1806. `);
  1807. expect(await finished).to.include('Electron');
  1808. });
  1809. });
  1810. describe('fetch', () => {
  1811. it('does not crash', async () => {
  1812. const server = http.createServer((req, res) => {
  1813. res.end('test');
  1814. });
  1815. defer(() => server.close());
  1816. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1817. const port = (server.address() as AddressInfo).port;
  1818. const w = new BrowserWindow({ show: false });
  1819. w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1820. const x = await w.webContents.executeJavaScript(`
  1821. fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader())
  1822. .then((reader) => {
  1823. return reader.read().then((r) => {
  1824. reader.cancel();
  1825. return r.value;
  1826. });
  1827. })
  1828. `);
  1829. expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116]));
  1830. });
  1831. });
  1832. describe('Promise', () => {
  1833. before(() => {
  1834. ipcMain.handle('ping', (e, arg) => arg);
  1835. });
  1836. after(() => {
  1837. ipcMain.removeHandler('ping');
  1838. });
  1839. itremote('resolves correctly in Node.js calls', async () => {
  1840. await new Promise<void>((resolve, reject) => {
  1841. class XElement extends HTMLElement {}
  1842. customElements.define('x-element', XElement);
  1843. setImmediate(() => {
  1844. let called = false;
  1845. Promise.resolve().then(() => {
  1846. if (called) resolve();
  1847. else reject(new Error('wrong sequence'));
  1848. });
  1849. document.createElement('x-element');
  1850. called = true;
  1851. });
  1852. });
  1853. });
  1854. itremote('resolves correctly in Electron calls', async () => {
  1855. await new Promise<void>((resolve, reject) => {
  1856. class YElement extends HTMLElement {}
  1857. customElements.define('y-element', YElement);
  1858. require('electron').ipcRenderer.invoke('ping').then(() => {
  1859. let called = false;
  1860. Promise.resolve().then(() => {
  1861. if (called) resolve();
  1862. else reject(new Error('wrong sequence'));
  1863. });
  1864. document.createElement('y-element');
  1865. called = true;
  1866. });
  1867. });
  1868. });
  1869. });
  1870. describe('synchronous prompts', () => {
  1871. describe('window.alert(message, title)', () => {
  1872. itremote('throws an exception when the arguments cannot be converted to strings', () => {
  1873. expect(() => {
  1874. window.alert({ toString: null });
  1875. }).to.throw('Cannot convert object to primitive value');
  1876. });
  1877. });
  1878. describe('window.confirm(message, title)', () => {
  1879. itremote('throws an exception when the arguments cannot be converted to strings', () => {
  1880. expect(() => {
  1881. (window.confirm as any)({ toString: null }, 'title');
  1882. }).to.throw('Cannot convert object to primitive value');
  1883. });
  1884. });
  1885. });
  1886. describe('window.history', () => {
  1887. describe('window.history.go(offset)', () => {
  1888. itremote('throws an exception when the argument cannot be converted to a string', () => {
  1889. expect(() => {
  1890. (window.history.go as any)({ toString: null });
  1891. }).to.throw('Cannot convert object to primitive value');
  1892. });
  1893. });
  1894. });
  1895. describe('console functions', () => {
  1896. itremote('should exist', () => {
  1897. expect(console.log, 'log').to.be.a('function');
  1898. expect(console.error, 'error').to.be.a('function');
  1899. expect(console.warn, 'warn').to.be.a('function');
  1900. expect(console.info, 'info').to.be.a('function');
  1901. expect(console.debug, 'debug').to.be.a('function');
  1902. expect(console.trace, 'trace').to.be.a('function');
  1903. expect(console.time, 'time').to.be.a('function');
  1904. expect(console.timeEnd, 'timeEnd').to.be.a('function');
  1905. });
  1906. });
  1907. ifdescribe(features.isTtsEnabled())('SpeechSynthesis', () => {
  1908. before(function () {
  1909. // TODO(nornagon): this is broken on CI, it triggers:
  1910. // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will
  1911. // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side
  1912. // (null text in SpeechSynthesisUtterance struct).
  1913. this.skip();
  1914. });
  1915. itremote('should emit lifecycle events', async () => {
  1916. const sentence = `long sentence which will take at least a few seconds to
  1917. utter so that it's possible to pause and resume before the end`;
  1918. const utter = new SpeechSynthesisUtterance(sentence);
  1919. // Create a dummy utterance so that speech synthesis state
  1920. // is initialized for later calls.
  1921. speechSynthesis.speak(new SpeechSynthesisUtterance());
  1922. speechSynthesis.cancel();
  1923. speechSynthesis.speak(utter);
  1924. // paused state after speak()
  1925. expect(speechSynthesis.paused).to.be.false();
  1926. await new Promise((resolve) => { utter.onstart = resolve; });
  1927. // paused state after start event
  1928. expect(speechSynthesis.paused).to.be.false();
  1929. speechSynthesis.pause();
  1930. // paused state changes async, right before the pause event
  1931. expect(speechSynthesis.paused).to.be.false();
  1932. await new Promise((resolve) => { utter.onpause = resolve; });
  1933. expect(speechSynthesis.paused).to.be.true();
  1934. speechSynthesis.resume();
  1935. await new Promise((resolve) => { utter.onresume = resolve; });
  1936. // paused state after resume event
  1937. expect(speechSynthesis.paused).to.be.false();
  1938. await new Promise((resolve) => { utter.onend = resolve; });
  1939. });
  1940. });
  1941. });
  1942. describe('font fallback', () => {
  1943. async function getRenderedFonts (html: string) {
  1944. const w = new BrowserWindow({ show: false });
  1945. try {
  1946. await w.loadURL(`data:text/html,${html}`);
  1947. w.webContents.debugger.attach();
  1948. const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
  1949. const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
  1950. await sendCommand('CSS.enable');
  1951. const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
  1952. return fonts;
  1953. } finally {
  1954. w.close();
  1955. }
  1956. }
  1957. it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
  1958. const html = '<body style="font-family: sans-serif">test</body>';
  1959. const fonts = await getRenderedFonts(html);
  1960. expect(fonts).to.be.an('array');
  1961. expect(fonts).to.have.length(1);
  1962. if (process.platform === 'win32') {
  1963. expect(fonts[0].familyName).to.equal('Arial');
  1964. } else if (process.platform === 'darwin') {
  1965. expect(fonts[0].familyName).to.equal('Helvetica');
  1966. } else if (process.platform === 'linux') {
  1967. expect(fonts[0].familyName).to.equal('DejaVu Sans');
  1968. } // I think this depends on the distro? We don't specify a default.
  1969. });
  1970. ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
  1971. const html = `
  1972. <html lang="ja-JP">
  1973. <head>
  1974. <meta charset="utf-8" />
  1975. </head>
  1976. <body style="font-family: sans-serif">test 智史</body>
  1977. </html>
  1978. `;
  1979. const fonts = await getRenderedFonts(html);
  1980. expect(fonts).to.be.an('array');
  1981. expect(fonts).to.have.length(1);
  1982. 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'); }
  1983. });
  1984. });
  1985. describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
  1986. const fullscreenChildHtml = promisify(fs.readFile)(
  1987. path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
  1988. );
  1989. let w: BrowserWindow, server: http.Server;
  1990. before(() => {
  1991. server = http.createServer(async (_req, res) => {
  1992. res.writeHead(200, { 'Content-Type': 'text/html' });
  1993. res.write(await fullscreenChildHtml);
  1994. res.end();
  1995. });
  1996. server.listen(8989, '127.0.0.1');
  1997. });
  1998. beforeEach(() => {
  1999. w = new BrowserWindow({
  2000. show: true,
  2001. fullscreen: true,
  2002. webPreferences: {
  2003. nodeIntegration: true,
  2004. nodeIntegrationInSubFrames: true,
  2005. contextIsolation: false
  2006. }
  2007. });
  2008. });
  2009. afterEach(async () => {
  2010. await closeAllWindows();
  2011. (w as any) = null;
  2012. server.close();
  2013. });
  2014. ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => {
  2015. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  2016. const html =
  2017. '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>';
  2018. w.loadURL(`data:text/html,${html}`);
  2019. await fullscreenChange;
  2020. const fullscreenWidth = await w.webContents.executeJavaScript(
  2021. "document.querySelector('iframe').offsetWidth"
  2022. );
  2023. expect(fullscreenWidth > 0).to.be.true();
  2024. await w.webContents.executeJavaScript(
  2025. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  2026. );
  2027. await delay(500);
  2028. const width = await w.webContents.executeJavaScript(
  2029. "document.querySelector('iframe').offsetWidth"
  2030. );
  2031. expect(width).to.equal(0);
  2032. });
  2033. ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => {
  2034. await emittedOnce(w, 'enter-full-screen');
  2035. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  2036. const html =
  2037. '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>';
  2038. w.loadURL(`data:text/html,${html}`);
  2039. await fullscreenChange;
  2040. const fullscreenWidth = await w.webContents.executeJavaScript(
  2041. "document.querySelector('iframe').offsetWidth"
  2042. );
  2043. expect(fullscreenWidth > 0).to.be.true();
  2044. await w.webContents.executeJavaScript(
  2045. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  2046. );
  2047. await emittedOnce(w.webContents, 'leave-html-full-screen');
  2048. const width = await w.webContents.executeJavaScript(
  2049. "document.querySelector('iframe').offsetWidth"
  2050. );
  2051. expect(width).to.equal(0);
  2052. w.setFullScreen(false);
  2053. await emittedOnce(w, 'leave-full-screen');
  2054. });
  2055. // TODO(jkleinsc) fix this flaky test on WOA
  2056. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => {
  2057. if (process.platform === 'darwin') await emittedOnce(w, 'enter-full-screen');
  2058. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  2059. w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
  2060. await fullscreenChange;
  2061. const fullscreenWidth = await w.webContents.executeJavaScript(
  2062. "document.querySelector('iframe').offsetWidth"
  2063. );
  2064. expect(fullscreenWidth > 0).to.true();
  2065. await w.webContents.executeJavaScript('document.exitFullscreen()');
  2066. const width = await w.webContents.executeJavaScript(
  2067. "document.querySelector('iframe').offsetWidth"
  2068. );
  2069. expect(width).to.equal(0);
  2070. });
  2071. });
  2072. describe('navigator.serial', () => {
  2073. let w: BrowserWindow;
  2074. before(async () => {
  2075. w = new BrowserWindow({
  2076. show: false
  2077. });
  2078. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2079. });
  2080. const getPorts: any = () => {
  2081. return w.webContents.executeJavaScript(`
  2082. navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
  2083. `, true);
  2084. };
  2085. after(closeAllWindows);
  2086. afterEach(() => {
  2087. session.defaultSession.setPermissionCheckHandler(null);
  2088. session.defaultSession.removeAllListeners('select-serial-port');
  2089. });
  2090. it('does not return a port if select-serial-port event is not defined', async () => {
  2091. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2092. const port = await getPorts();
  2093. expect(port).to.equal('NotFoundError: No port selected by the user.');
  2094. });
  2095. it('does not return a port when permission denied', async () => {
  2096. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2097. callback(portList[0].portId);
  2098. });
  2099. session.defaultSession.setPermissionCheckHandler(() => false);
  2100. const port = await getPorts();
  2101. expect(port).to.equal('NotFoundError: No port selected by the user.');
  2102. });
  2103. it('does not crash when select-serial-port is called with an invalid port', async () => {
  2104. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2105. callback('i-do-not-exist');
  2106. });
  2107. const port = await getPorts();
  2108. expect(port).to.equal('NotFoundError: No port selected by the user.');
  2109. });
  2110. it('returns a port when select-serial-port event is defined', async () => {
  2111. let havePorts = false;
  2112. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2113. if (portList.length > 0) {
  2114. havePorts = true;
  2115. callback(portList[0].portId);
  2116. } else {
  2117. callback('');
  2118. }
  2119. });
  2120. const port = await getPorts();
  2121. if (havePorts) {
  2122. expect(port).to.equal('[object SerialPort]');
  2123. } else {
  2124. expect(port).to.equal('NotFoundError: No port selected by the user.');
  2125. }
  2126. });
  2127. it('navigator.serial.getPorts() returns values', async () => {
  2128. let havePorts = false;
  2129. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2130. if (portList.length > 0) {
  2131. havePorts = true;
  2132. callback(portList[0].portId);
  2133. } else {
  2134. callback('');
  2135. }
  2136. });
  2137. await getPorts();
  2138. if (havePorts) {
  2139. const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
  2140. expect(grantedPorts).to.not.be.empty();
  2141. }
  2142. });
  2143. });
  2144. describe('navigator.clipboard', () => {
  2145. let w: BrowserWindow;
  2146. before(async () => {
  2147. w = new BrowserWindow({
  2148. webPreferences: {
  2149. enableBlinkFeatures: 'Serial'
  2150. }
  2151. });
  2152. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2153. });
  2154. const readClipboard: any = () => {
  2155. return w.webContents.executeJavaScript(`
  2156. navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
  2157. `, true);
  2158. };
  2159. after(closeAllWindows);
  2160. afterEach(() => {
  2161. session.defaultSession.setPermissionRequestHandler(null);
  2162. });
  2163. it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
  2164. const clipboard = await readClipboard();
  2165. expect(clipboard).to.not.equal('Read permission denied.');
  2166. });
  2167. it('returns an error when permission denied', async () => {
  2168. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2169. if (permission === 'clipboard-read') {
  2170. callback(false);
  2171. } else {
  2172. callback(true);
  2173. }
  2174. });
  2175. const clipboard = await readClipboard();
  2176. expect(clipboard).to.equal('Read permission denied.');
  2177. });
  2178. it('returns clipboard contents when permission is granted', async () => {
  2179. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2180. if (permission === 'clipboard-read') {
  2181. callback(true);
  2182. } else {
  2183. callback(false);
  2184. }
  2185. });
  2186. const clipboard = await readClipboard();
  2187. expect(clipboard).to.not.equal('Read permission denied.');
  2188. });
  2189. });
  2190. ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
  2191. let w: BrowserWindow;
  2192. const expectedBadgeCount = 42;
  2193. const fireAppBadgeAction: any = (action: string, value: any) => {
  2194. return w.webContents.executeJavaScript(`
  2195. navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
  2196. };
  2197. // For some reason on macOS changing the badge count doesn't happen right away, so wait
  2198. // until it changes.
  2199. async function waitForBadgeCount (value: number) {
  2200. let badgeCount = app.getBadgeCount();
  2201. while (badgeCount !== value) {
  2202. await new Promise(resolve => setTimeout(resolve, 10));
  2203. badgeCount = app.getBadgeCount();
  2204. }
  2205. return badgeCount;
  2206. }
  2207. describe('in the renderer', () => {
  2208. before(async () => {
  2209. w = new BrowserWindow({
  2210. show: false
  2211. });
  2212. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2213. });
  2214. after(() => {
  2215. app.badgeCount = 0;
  2216. closeAllWindows();
  2217. });
  2218. it('setAppBadge can set a numerical value', async () => {
  2219. const result = await fireAppBadgeAction('set', expectedBadgeCount);
  2220. expect(result).to.equal('success');
  2221. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2222. });
  2223. it('setAppBadge can set an empty(dot) value', async () => {
  2224. const result = await fireAppBadgeAction('set');
  2225. expect(result).to.equal('success');
  2226. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  2227. });
  2228. it('clearAppBadge can clear a value', async () => {
  2229. let result = await fireAppBadgeAction('set', expectedBadgeCount);
  2230. expect(result).to.equal('success');
  2231. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2232. result = await fireAppBadgeAction('clear');
  2233. expect(result).to.equal('success');
  2234. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  2235. });
  2236. });
  2237. describe('in a service worker', () => {
  2238. beforeEach(async () => {
  2239. w = new BrowserWindow({
  2240. show: false,
  2241. webPreferences: {
  2242. nodeIntegration: true,
  2243. partition: 'sw-file-scheme-spec',
  2244. contextIsolation: false
  2245. }
  2246. });
  2247. });
  2248. afterEach(() => {
  2249. app.badgeCount = 0;
  2250. closeAllWindows();
  2251. });
  2252. it('setAppBadge can be called in a ServiceWorker', (done) => {
  2253. w.webContents.on('ipc-message', (event, channel, message) => {
  2254. if (channel === 'reload') {
  2255. w.webContents.reload();
  2256. } else if (channel === 'error') {
  2257. done(message);
  2258. } else if (channel === 'response') {
  2259. expect(message).to.equal('SUCCESS setting app badge');
  2260. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2261. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  2262. storages: ['serviceworkers']
  2263. }).then(() => done());
  2264. }
  2265. });
  2266. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  2267. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
  2268. });
  2269. it('clearAppBadge can be called in a ServiceWorker', (done) => {
  2270. w.webContents.on('ipc-message', (event, channel, message) => {
  2271. if (channel === 'reload') {
  2272. w.webContents.reload();
  2273. } else if (channel === 'setAppBadge') {
  2274. expect(message).to.equal('SUCCESS setting app badge');
  2275. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2276. } else if (channel === 'error') {
  2277. done(message);
  2278. } else if (channel === 'response') {
  2279. expect(message).to.equal('SUCCESS clearing app badge');
  2280. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2281. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  2282. storages: ['serviceworkers']
  2283. }).then(() => done());
  2284. }
  2285. });
  2286. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  2287. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
  2288. });
  2289. });
  2290. });
  2291. describe('navigator.bluetooth', () => {
  2292. let w: BrowserWindow;
  2293. before(async () => {
  2294. w = new BrowserWindow({
  2295. show: false,
  2296. webPreferences: {
  2297. enableBlinkFeatures: 'WebBluetooth'
  2298. }
  2299. });
  2300. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2301. });
  2302. after(closeAllWindows);
  2303. it('can request bluetooth devices', async () => {
  2304. const bluetooth = await w.webContents.executeJavaScript(`
  2305. navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
  2306. expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
  2307. });
  2308. });
  2309. describe('navigator.hid', () => {
  2310. let w: BrowserWindow;
  2311. let server: http.Server;
  2312. let serverUrl: string;
  2313. before(async () => {
  2314. w = new BrowserWindow({
  2315. show: false
  2316. });
  2317. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2318. server = http.createServer((req, res) => {
  2319. res.setHeader('Content-Type', 'text/html');
  2320. res.end('<body>');
  2321. });
  2322. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  2323. serverUrl = `http://localhost:${(server.address() as any).port}`;
  2324. });
  2325. const requestDevices: any = () => {
  2326. return w.webContents.executeJavaScript(`
  2327. navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
  2328. `, true);
  2329. };
  2330. after(() => {
  2331. server.close();
  2332. closeAllWindows();
  2333. });
  2334. afterEach(() => {
  2335. session.defaultSession.setPermissionCheckHandler(null);
  2336. session.defaultSession.setDevicePermissionHandler(null);
  2337. session.defaultSession.removeAllListeners('select-hid-device');
  2338. });
  2339. it('does not return a device if select-hid-device event is not defined', async () => {
  2340. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2341. const device = await requestDevices();
  2342. expect(device).to.equal('');
  2343. });
  2344. it('does not return a device when permission denied', async () => {
  2345. let selectFired = false;
  2346. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2347. selectFired = true;
  2348. callback();
  2349. });
  2350. session.defaultSession.setPermissionCheckHandler(() => false);
  2351. const device = await requestDevices();
  2352. expect(selectFired).to.be.false();
  2353. expect(device).to.equal('');
  2354. });
  2355. it('returns a device when select-hid-device event is defined', async () => {
  2356. let haveDevices = false;
  2357. let selectFired = false;
  2358. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2359. expect(details.frame).to.have.ownProperty('frameTreeNodeId').that.is.a('number');
  2360. selectFired = true;
  2361. if (details.deviceList.length > 0) {
  2362. haveDevices = true;
  2363. callback(details.deviceList[0].deviceId);
  2364. } else {
  2365. callback();
  2366. }
  2367. });
  2368. const device = await requestDevices();
  2369. expect(selectFired).to.be.true();
  2370. if (haveDevices) {
  2371. expect(device).to.contain('[object HIDDevice]');
  2372. } else {
  2373. expect(device).to.equal('');
  2374. }
  2375. if (process.arch === 'arm64' || process.arch === 'arm') {
  2376. // arm CI returns HID devices - this block may need to change if CI hardware changes.
  2377. expect(haveDevices).to.be.true();
  2378. // Verify that navigation will clear device permissions
  2379. const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  2380. expect(grantedDevices).to.not.be.empty();
  2381. w.loadURL(serverUrl);
  2382. const [,,,,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-navigate');
  2383. const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
  2384. expect(frame).to.not.be.empty();
  2385. if (frame) {
  2386. const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
  2387. expect(grantedDevicesOnNewPage).to.be.empty();
  2388. }
  2389. }
  2390. });
  2391. it('returns a device when DevicePermissionHandler is defined', async () => {
  2392. let haveDevices = false;
  2393. let selectFired = false;
  2394. let gotDevicePerms = false;
  2395. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2396. selectFired = true;
  2397. if (details.deviceList.length > 0) {
  2398. const foundDevice = details.deviceList.find((device) => {
  2399. if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
  2400. haveDevices = true;
  2401. return true;
  2402. }
  2403. });
  2404. if (foundDevice) {
  2405. callback(foundDevice.deviceId);
  2406. return;
  2407. }
  2408. }
  2409. callback();
  2410. });
  2411. session.defaultSession.setDevicePermissionHandler(() => {
  2412. gotDevicePerms = true;
  2413. return true;
  2414. });
  2415. await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
  2416. const device = await requestDevices();
  2417. expect(selectFired).to.be.true();
  2418. if (haveDevices) {
  2419. expect(device).to.contain('[object HIDDevice]');
  2420. expect(gotDevicePerms).to.be.true();
  2421. } else {
  2422. expect(device).to.equal('');
  2423. }
  2424. });
  2425. it('excludes a device when a exclusionFilter is specified', async () => {
  2426. const exclusionFilters = <any>[];
  2427. let haveDevices = false;
  2428. let checkForExcludedDevice = false;
  2429. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2430. if (details.deviceList.length > 0) {
  2431. details.deviceList.find((device) => {
  2432. if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
  2433. if (checkForExcludedDevice) {
  2434. const compareDevice = {
  2435. vendorId: device.vendorId,
  2436. productId: device.productId
  2437. };
  2438. expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned');
  2439. } else {
  2440. haveDevices = true;
  2441. exclusionFilters.push({
  2442. vendorId: device.vendorId,
  2443. productId: device.productId
  2444. });
  2445. return true;
  2446. }
  2447. }
  2448. });
  2449. }
  2450. callback();
  2451. });
  2452. await requestDevices();
  2453. if (haveDevices) {
  2454. // We have devices to exclude, so check if exclusionFilters work
  2455. checkForExcludedDevice = true;
  2456. await w.webContents.executeJavaScript(`
  2457. navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString());
  2458. `, true);
  2459. }
  2460. });
  2461. it('supports device.forget()', async () => {
  2462. let deletedDeviceFromEvent;
  2463. let haveDevices = false;
  2464. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2465. if (details.deviceList.length > 0) {
  2466. haveDevices = true;
  2467. callback(details.deviceList[0].deviceId);
  2468. } else {
  2469. callback();
  2470. }
  2471. });
  2472. w.webContents.session.on('hid-device-revoked', (event, details) => {
  2473. deletedDeviceFromEvent = details.device;
  2474. });
  2475. await requestDevices();
  2476. if (haveDevices) {
  2477. const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  2478. if (grantedDevices.length > 0) {
  2479. const deletedDevice = await w.webContents.executeJavaScript(`
  2480. navigator.hid.getDevices().then(devices => {
  2481. devices[0].forget();
  2482. return {
  2483. vendorId: devices[0].vendorId,
  2484. productId: devices[0].productId,
  2485. name: devices[0].productName
  2486. }
  2487. })
  2488. `);
  2489. const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  2490. expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
  2491. if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) {
  2492. expect(deletedDeviceFromEvent).to.include(deletedDevice);
  2493. }
  2494. }
  2495. }
  2496. });
  2497. });