chromium-spec.ts 149 KB

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