chromium-spec.ts 142 KB

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