chromium-spec.ts 146 KB

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