chromium-spec.ts 145 KB

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