chromium-spec.ts 139 KB

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