chromium-spec.ts 149 KB

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