chromium-spec.ts 141 KB

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