chromium-spec.ts 144 KB

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