chromium-spec.ts 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326
  1. import { expect } from 'chai';
  2. import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } 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 { promisify } from 'node:util';
  12. import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers';
  13. import { PipeTransport } from './pipe-transport';
  14. import * as ws from 'ws';
  15. import { setTimeout } from 'node:timers/promises';
  16. 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 new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  51. const bw = new BrowserWindow({ show: false });
  52. try {
  53. const reportGenerated = once(reporting, 'report');
  54. await bw.loadURL(`https://localhost:${(server.address() as any).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 load successfully but its body will be emptied out
  197. // by CORB, so we don't expect a syntax error.
  198. s.onload = () => { 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.replace(/\\/g, '/'),
  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.replace(/(\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.languages', () => {
  541. it('should return the system locale only', async () => {
  542. const appLocale = app.getLocale();
  543. const w = new BrowserWindow({ show: false });
  544. await w.loadURL('about:blank');
  545. const languages = await w.webContents.executeJavaScript('navigator.languages');
  546. expect(languages.length).to.be.greaterThan(0);
  547. expect(languages).to.contain(appLocale);
  548. });
  549. });
  550. describe('navigator.serviceWorker', () => {
  551. it('should register for file scheme', (done) => {
  552. const w = new BrowserWindow({
  553. show: false,
  554. webPreferences: {
  555. nodeIntegration: true,
  556. partition: 'sw-file-scheme-spec',
  557. contextIsolation: false
  558. }
  559. });
  560. w.webContents.on('ipc-message', (event, channel, message) => {
  561. if (channel === 'reload') {
  562. w.webContents.reload();
  563. } else if (channel === 'error') {
  564. done(message);
  565. } else if (channel === 'response') {
  566. expect(message).to.equal('Hello from serviceWorker!');
  567. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  568. storages: ['serviceworkers']
  569. }).then(() => done());
  570. }
  571. });
  572. w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
  573. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  574. });
  575. it('should register for intercepted file scheme', (done) => {
  576. const customSession = session.fromPartition('intercept-file');
  577. customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
  578. let file = url.parse(request.url).pathname!;
  579. if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
  580. const content = fs.readFileSync(path.normalize(file));
  581. const ext = path.extname(file);
  582. let type = 'text/html';
  583. if (ext === '.js') type = 'application/javascript';
  584. callback({ data: content, mimeType: type } as any);
  585. });
  586. const w = new BrowserWindow({
  587. show: false,
  588. webPreferences: {
  589. nodeIntegration: true,
  590. session: customSession,
  591. contextIsolation: false
  592. }
  593. });
  594. w.webContents.on('ipc-message', (event, channel, message) => {
  595. if (channel === 'reload') {
  596. w.webContents.reload();
  597. } else if (channel === 'error') {
  598. done(`unexpected error : ${message}`);
  599. } else if (channel === 'response') {
  600. expect(message).to.equal('Hello from serviceWorker!');
  601. customSession.clearStorageData({
  602. storages: ['serviceworkers']
  603. }).then(() => {
  604. customSession.protocol.uninterceptProtocol('file');
  605. done();
  606. });
  607. }
  608. });
  609. w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
  610. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  611. });
  612. it('should register for custom scheme', (done) => {
  613. const customSession = session.fromPartition('custom-scheme');
  614. customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => {
  615. let file = url.parse(request.url).pathname!;
  616. if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
  617. callback({ path: path.normalize(file) } as any);
  618. });
  619. const w = new BrowserWindow({
  620. show: false,
  621. webPreferences: {
  622. nodeIntegration: true,
  623. session: customSession,
  624. contextIsolation: false
  625. }
  626. });
  627. w.webContents.on('ipc-message', (event, channel, message) => {
  628. if (channel === 'reload') {
  629. w.webContents.reload();
  630. } else if (channel === 'error') {
  631. done(`unexpected error : ${message}`);
  632. } else if (channel === 'response') {
  633. expect(message).to.equal('Hello from serviceWorker!');
  634. customSession.clearStorageData({
  635. storages: ['serviceworkers']
  636. }).then(() => {
  637. customSession.protocol.uninterceptProtocol(serviceWorkerScheme);
  638. done();
  639. });
  640. }
  641. });
  642. w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
  643. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html'));
  644. });
  645. it('should not allow nodeIntegrationInWorker', async () => {
  646. const w = new BrowserWindow({
  647. show: false,
  648. webPreferences: {
  649. nodeIntegration: true,
  650. nodeIntegrationInWorker: true,
  651. partition: 'sw-file-scheme-worker-spec',
  652. contextIsolation: false
  653. }
  654. });
  655. await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`);
  656. const data = await w.webContents.executeJavaScript(`
  657. navigator.serviceWorker.register('worker-no-node.js', {
  658. scope: './'
  659. }).then(() => navigator.serviceWorker.ready)
  660. new Promise((resolve) => {
  661. navigator.serviceWorker.onmessage = event => resolve(event.data);
  662. });
  663. `);
  664. expect(data).to.equal('undefined undefined undefined undefined');
  665. });
  666. });
  667. describe('navigator.geolocation', () => {
  668. ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => {
  669. const w = new BrowserWindow({
  670. show: false,
  671. webPreferences: {
  672. nodeIntegration: true,
  673. partition: 'geolocation-spec',
  674. contextIsolation: false
  675. }
  676. });
  677. const message = once(w.webContents, 'ipc-message');
  678. w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
  679. if (permission === 'geolocation') {
  680. callback(false);
  681. } else {
  682. callback(true);
  683. }
  684. });
  685. w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
  686. const [, channel] = await message;
  687. expect(channel).to.equal('success', 'unexpected response from geolocation api');
  688. });
  689. ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => {
  690. const w = new BrowserWindow({
  691. show: false,
  692. webPreferences: {
  693. partition: 'geolocation-spec'
  694. }
  695. });
  696. w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => {
  697. callback(true);
  698. });
  699. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  700. const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) =>
  701. navigator.geolocation.getCurrentPosition(
  702. x => resolve({coords: x.coords, timestamp: x.timestamp}),
  703. err => reject(new Error(err.message))))`);
  704. expect(position).to.have.property('coords');
  705. expect(position).to.have.property('timestamp');
  706. });
  707. });
  708. describe('web workers', () => {
  709. let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
  710. afterEach(() => {
  711. if (appProcess && !appProcess.killed) {
  712. appProcess.kill();
  713. appProcess = undefined;
  714. }
  715. });
  716. it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => {
  717. const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths');
  718. appProcess = ChildProcess.spawn(process.execPath, [appPath]);
  719. const [code] = await once(appProcess, 'exit');
  720. expect(code).to.equal(0);
  721. });
  722. it('Worker can work', async () => {
  723. const w = new BrowserWindow({ show: false });
  724. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  725. const data = await w.webContents.executeJavaScript(`
  726. const worker = new Worker('../workers/worker.js');
  727. const message = 'ping';
  728. const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; });
  729. worker.postMessage(message);
  730. eventPromise.then(t => t.data)
  731. `);
  732. expect(data).to.equal('ping');
  733. });
  734. it('Worker has no node integration by default', async () => {
  735. const w = new BrowserWindow({ show: false });
  736. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  737. const data = await w.webContents.executeJavaScript(`
  738. const worker = new Worker('../workers/worker_node.js');
  739. new Promise((resolve) => { worker.onmessage = e => resolve(e.data); })
  740. `);
  741. expect(data).to.equal('undefined undefined undefined undefined');
  742. });
  743. it('Worker has node integration with nodeIntegrationInWorker', async () => {
  744. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } });
  745. w.loadURL(`file://${fixturesPath}/pages/worker.html`);
  746. const [, data] = await once(ipcMain, 'worker-result');
  747. expect(data).to.equal('object function object function');
  748. });
  749. describe('SharedWorker', () => {
  750. it('can work', async () => {
  751. const w = new BrowserWindow({ show: false });
  752. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  753. const data = await w.webContents.executeJavaScript(`
  754. const worker = new SharedWorker('../workers/shared_worker.js');
  755. const message = 'ping';
  756. const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); });
  757. worker.port.postMessage(message);
  758. eventPromise
  759. `);
  760. expect(data).to.equal('ping');
  761. });
  762. it('has no node integration by default', async () => {
  763. const w = new BrowserWindow({ show: false });
  764. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  765. const data = await w.webContents.executeJavaScript(`
  766. const worker = new SharedWorker('../workers/shared_worker_node.js');
  767. new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
  768. `);
  769. expect(data).to.equal('undefined undefined undefined undefined');
  770. });
  771. it('does not have node integration with nodeIntegrationInWorker', async () => {
  772. const w = new BrowserWindow({
  773. show: false,
  774. webPreferences: {
  775. nodeIntegration: true,
  776. nodeIntegrationInWorker: true,
  777. contextIsolation: false
  778. }
  779. });
  780. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  781. const data = await w.webContents.executeJavaScript(`
  782. const worker = new SharedWorker('../workers/shared_worker_node.js');
  783. new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
  784. `);
  785. expect(data).to.equal('undefined undefined undefined undefined');
  786. });
  787. });
  788. });
  789. describe('form submit', () => {
  790. let server: http.Server;
  791. let serverUrl: string;
  792. before(async () => {
  793. server = http.createServer((req, res) => {
  794. let body = '';
  795. req.on('data', (chunk) => {
  796. body += chunk;
  797. });
  798. res.setHeader('Content-Type', 'application/json');
  799. req.on('end', () => {
  800. res.end(`body:${body}`);
  801. });
  802. });
  803. serverUrl = (await listen(server)).url;
  804. });
  805. after(async () => {
  806. server.close();
  807. await closeAllWindows();
  808. });
  809. [true, false].forEach((isSandboxEnabled) =>
  810. describe(`sandbox=${isSandboxEnabled}`, () => {
  811. it('posts data in the same window', async () => {
  812. const w = new BrowserWindow({
  813. show: false,
  814. webPreferences: {
  815. sandbox: isSandboxEnabled
  816. }
  817. });
  818. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  819. const loadPromise = once(w.webContents, 'did-finish-load');
  820. w.webContents.executeJavaScript(`
  821. const form = document.querySelector('form')
  822. form.action = '${serverUrl}';
  823. form.submit();
  824. `);
  825. await loadPromise;
  826. const res = await w.webContents.executeJavaScript('document.body.innerText');
  827. expect(res).to.equal('body:greeting=hello');
  828. });
  829. it('posts data to a new window with target=_blank', async () => {
  830. const w = new BrowserWindow({
  831. show: false,
  832. webPreferences: {
  833. sandbox: isSandboxEnabled
  834. }
  835. });
  836. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  837. const windowCreatedPromise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
  838. w.webContents.executeJavaScript(`
  839. const form = document.querySelector('form')
  840. form.action = '${serverUrl}';
  841. form.target = '_blank';
  842. form.submit();
  843. `);
  844. const [, newWin] = await windowCreatedPromise;
  845. const res = await newWin.webContents.executeJavaScript('document.body.innerText');
  846. expect(res).to.equal('body:greeting=hello');
  847. });
  848. })
  849. );
  850. });
  851. describe('window.open', () => {
  852. for (const show of [true, false]) {
  853. it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => {
  854. const w = new BrowserWindow({ show });
  855. // toggle visibility
  856. if (show) {
  857. w.hide();
  858. } else {
  859. w.show();
  860. }
  861. defer(() => { w.close(); });
  862. const promise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
  863. w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
  864. const [, newWindow] = await promise;
  865. expect(newWindow.isVisible()).to.equal(true);
  866. });
  867. }
  868. // FIXME(zcbenz): This test is making the spec runner hang on exit on Windows.
  869. ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => {
  870. const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html'));
  871. windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`);
  872. const w = new BrowserWindow({ show: false });
  873. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  874. const { eventData } = await w.webContents.executeJavaScript(`(async () => {
  875. const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
  876. const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false')
  877. const e = await message
  878. b.close();
  879. return {
  880. eventData: e.data
  881. }
  882. })()`);
  883. expect(eventData.isProcessGlobalUndefined).to.be.true();
  884. });
  885. it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
  886. // NB. webSecurity is disabled because native window.open() is not
  887. // allowed to load devtools:// URLs.
  888. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } });
  889. w.loadURL('about:blank');
  890. w.webContents.executeJavaScript(`
  891. { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null }
  892. `);
  893. const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
  894. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  895. expect(typeofProcessGlobal).to.equal('undefined');
  896. });
  897. it('can disable node integration when it is enabled on the parent window', async () => {
  898. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  899. w.loadURL('about:blank');
  900. w.webContents.executeJavaScript(`
  901. { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null }
  902. `);
  903. const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
  904. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  905. expect(typeofProcessGlobal).to.equal('undefined');
  906. });
  907. // TODO(jkleinsc) fix this flaky test on WOA
  908. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => {
  909. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } });
  910. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  911. const windowUrl = require('node:url').format({
  912. pathname: `${fixturesPath}/pages/window-no-javascript.html`,
  913. protocol: 'file',
  914. slashes: true
  915. });
  916. w.webContents.executeJavaScript(`
  917. { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null }
  918. `);
  919. const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
  920. await once(contents, 'did-finish-load');
  921. // Click link on page
  922. contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
  923. contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
  924. const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow];
  925. const preferences = window.webContents.getLastWebPreferences();
  926. expect(preferences!.javascript).to.be.false();
  927. });
  928. it('defines a window.location getter', async () => {
  929. let targetURL: string;
  930. if (process.platform === 'win32') {
  931. targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
  932. } else {
  933. targetURL = `file://${fixturesPath}/pages/base-page.html`;
  934. }
  935. const w = new BrowserWindow({ show: false });
  936. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  937. w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
  938. const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow];
  939. await once(window.webContents, 'did-finish-load');
  940. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
  941. });
  942. it('defines a window.location setter', async () => {
  943. const w = new BrowserWindow({ show: false });
  944. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  945. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  946. const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
  947. await once(webContents, 'did-finish-load');
  948. // When it loads, redirect
  949. w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  950. await once(webContents, 'did-finish-load');
  951. });
  952. it('defines a window.location.href setter', async () => {
  953. const w = new BrowserWindow({ show: false });
  954. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  955. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  956. const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
  957. await once(webContents, 'did-finish-load');
  958. // When it loads, redirect
  959. w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  960. await once(webContents, 'did-finish-load');
  961. });
  962. it('open a blank page when no URL is specified', async () => {
  963. const w = new BrowserWindow({ show: false });
  964. w.loadURL('about:blank');
  965. w.webContents.executeJavaScript('{ b = window.open(); null }');
  966. const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
  967. await once(webContents, 'did-finish-load');
  968. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  969. });
  970. it('open a blank page when an empty URL is specified', async () => {
  971. const w = new BrowserWindow({ show: false });
  972. w.loadURL('about:blank');
  973. w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
  974. const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
  975. await once(webContents, 'did-finish-load');
  976. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  977. });
  978. it('does not throw an exception when the frameName is a built-in object property', async () => {
  979. const w = new BrowserWindow({ show: false });
  980. w.loadURL('about:blank');
  981. w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
  982. const frameName = await new Promise((resolve) => {
  983. w.webContents.setWindowOpenHandler(details => {
  984. setImmediate(() => resolve(details.frameName));
  985. return { action: 'allow' };
  986. });
  987. });
  988. expect(frameName).to.equal('__proto__');
  989. });
  990. it('works when used in conjunction with the vm module', async () => {
  991. const w = new BrowserWindow({
  992. show: false,
  993. webPreferences: {
  994. nodeIntegration: true,
  995. contextIsolation: false
  996. }
  997. });
  998. await w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  999. const { contextObject } = await w.webContents.executeJavaScript(`(async () => {
  1000. const vm = require('node:vm');
  1001. const contextObject = { count: 1, type: 'gecko' };
  1002. window.open('');
  1003. vm.runInNewContext('count += 1; type = "chameleon";', contextObject);
  1004. return { contextObject };
  1005. })()`);
  1006. expect(contextObject).to.deep.equal({ count: 2, type: 'chameleon' });
  1007. });
  1008. // FIXME(nornagon): I'm not sure this ... ever was correct?
  1009. xit('inherit options of parent window', async () => {
  1010. const w = new BrowserWindow({ show: false, width: 123, height: 456 });
  1011. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  1012. const url = `file://${fixturesPath}/pages/window-open-size.html`;
  1013. const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => {
  1014. const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
  1015. const b = window.open(${JSON.stringify(url)}, '', 'show=false')
  1016. const e = await message
  1017. b.close();
  1018. const width = outerWidth;
  1019. const height = outerHeight;
  1020. return {
  1021. width,
  1022. height,
  1023. eventData: e.data
  1024. }
  1025. })()`);
  1026. expect(eventData).to.equal(`size: ${width} ${height}`);
  1027. expect(eventData).to.equal('size: 123 456');
  1028. });
  1029. it('does not override child options', async () => {
  1030. const w = new BrowserWindow({ show: false });
  1031. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  1032. const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`;
  1033. const { eventData } = await w.webContents.executeJavaScript(`(async () => {
  1034. const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
  1035. const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450')
  1036. const e = await message
  1037. b.close();
  1038. return { eventData: e.data }
  1039. })()`);
  1040. expect(eventData).to.equal('size: 350 450');
  1041. });
  1042. it('loads preload script after setting opener to null', async () => {
  1043. const w = new BrowserWindow({ show: false });
  1044. w.webContents.setWindowOpenHandler(() => ({
  1045. action: 'allow',
  1046. overrideBrowserWindowOptions: {
  1047. webPreferences: {
  1048. preload: path.join(fixturesPath, 'module', 'preload.js')
  1049. }
  1050. }
  1051. }));
  1052. w.loadURL('about:blank');
  1053. w.webContents.executeJavaScript('window.child = window.open(); child.opener = null');
  1054. const [, { webContents }] = await once(app, 'browser-window-created');
  1055. const [,, message] = await once(webContents, 'console-message');
  1056. expect(message).to.equal('{"require":"function","module":"undefined","process":"object","Buffer":"function"}');
  1057. });
  1058. it('disables the <webview> tag when it is disabled on the parent window', async () => {
  1059. const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html'));
  1060. windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`);
  1061. const w = new BrowserWindow({ show: false });
  1062. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  1063. const { eventData } = await w.webContents.executeJavaScript(`(async () => {
  1064. const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
  1065. const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no')
  1066. const e = await message
  1067. b.close();
  1068. return { eventData: e.data }
  1069. })()`);
  1070. expect(eventData.isWebViewGlobalUndefined).to.be.true();
  1071. });
  1072. it('throws an exception when the arguments cannot be converted to strings', async () => {
  1073. const w = new BrowserWindow({ show: false });
  1074. w.loadURL('about:blank');
  1075. await expect(
  1076. w.webContents.executeJavaScript('window.open(\'\', { toString: null })')
  1077. ).to.eventually.be.rejected();
  1078. await expect(
  1079. w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })')
  1080. ).to.eventually.be.rejected();
  1081. });
  1082. it('does not throw an exception when the features include webPreferences', async () => {
  1083. const w = new BrowserWindow({ show: false });
  1084. w.loadURL('about:blank');
  1085. await expect(
  1086. w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null')
  1087. ).to.eventually.be.fulfilled();
  1088. });
  1089. });
  1090. describe('window.opener', () => {
  1091. it('is null for main window', async () => {
  1092. const w = new BrowserWindow({
  1093. show: false,
  1094. webPreferences: {
  1095. nodeIntegration: true,
  1096. contextIsolation: false
  1097. }
  1098. });
  1099. w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
  1100. const [, channel, opener] = await once(w.webContents, 'ipc-message');
  1101. expect(channel).to.equal('opener');
  1102. expect(opener).to.equal(null);
  1103. });
  1104. it('is not null for window opened by window.open', async () => {
  1105. const w = new BrowserWindow({
  1106. show: false,
  1107. webPreferences: {
  1108. nodeIntegration: true,
  1109. contextIsolation: false
  1110. }
  1111. });
  1112. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  1113. const windowUrl = `file://${fixturesPath}/pages/window-opener.html`;
  1114. const eventData = await w.webContents.executeJavaScript(`
  1115. const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
  1116. new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data);
  1117. `);
  1118. expect(eventData).to.equal('object');
  1119. });
  1120. });
  1121. describe('window.opener.postMessage', () => {
  1122. it('sets source and origin correctly', async () => {
  1123. const w = new BrowserWindow({ show: false });
  1124. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  1125. const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`;
  1126. const { sourceIsChild, origin } = await w.webContents.executeJavaScript(`
  1127. const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
  1128. new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({
  1129. sourceIsChild: e.source === b,
  1130. origin: e.origin
  1131. }));
  1132. `);
  1133. expect(sourceIsChild).to.be.true();
  1134. expect(origin).to.equal('file://');
  1135. });
  1136. it('supports windows opened from a <webview>', async () => {
  1137. const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
  1138. w.loadURL('about:blank');
  1139. const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html'));
  1140. childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`);
  1141. const message = await w.webContents.executeJavaScript(`
  1142. const webview = new WebView();
  1143. webview.allowpopups = true;
  1144. webview.setAttribute('webpreferences', 'contextIsolation=no');
  1145. webview.src = ${JSON.stringify(childWindowUrl)}
  1146. const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true}));
  1147. document.body.appendChild(webview);
  1148. consoleMessage.then(e => e.message)
  1149. `);
  1150. expect(message).to.equal('message');
  1151. });
  1152. describe('targetOrigin argument', () => {
  1153. let serverURL: string;
  1154. let server: any;
  1155. beforeEach(async () => {
  1156. server = http.createServer((req, res) => {
  1157. res.writeHead(200);
  1158. const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html');
  1159. res.end(fs.readFileSync(filePath, 'utf8'));
  1160. });
  1161. serverURL = (await listen(server)).url;
  1162. });
  1163. afterEach(() => {
  1164. server.close();
  1165. });
  1166. it('delivers messages that match the origin', async () => {
  1167. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1168. w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  1169. const data = await w.webContents.executeJavaScript(`
  1170. window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes');
  1171. new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data)
  1172. `);
  1173. expect(data).to.equal('deliver');
  1174. });
  1175. });
  1176. });
  1177. describe('IdleDetection', () => {
  1178. afterEach(closeAllWindows);
  1179. afterEach(() => {
  1180. session.defaultSession.setPermissionCheckHandler(null);
  1181. session.defaultSession.setPermissionRequestHandler(null);
  1182. });
  1183. it('can grant a permission request', async () => {
  1184. session.defaultSession.setPermissionRequestHandler(
  1185. (_wc, permission, callback) => {
  1186. callback(permission === 'idle-detection');
  1187. }
  1188. );
  1189. const w = new BrowserWindow({ show: false });
  1190. await w.loadFile(path.join(fixturesPath, 'pages', 'button.html'));
  1191. const permission = await w.webContents.executeJavaScript(`
  1192. new Promise((resolve, reject) => {
  1193. const button = document.getElementById('button');
  1194. button.addEventListener("click", async () => {
  1195. const permission = await IdleDetector.requestPermission();
  1196. resolve(permission);
  1197. });
  1198. button.click();
  1199. });
  1200. `, true);
  1201. expect(permission).to.eq('granted');
  1202. });
  1203. it('can deny a permission request', async () => {
  1204. session.defaultSession.setPermissionRequestHandler(
  1205. (_wc, permission, callback) => {
  1206. callback(permission !== 'idle-detection');
  1207. }
  1208. );
  1209. const w = new BrowserWindow({ show: false });
  1210. await w.loadFile(path.join(fixturesPath, 'pages', 'button.html'));
  1211. const permission = await w.webContents.executeJavaScript(`
  1212. new Promise((resolve, reject) => {
  1213. const button = document.getElementById('button');
  1214. button.addEventListener("click", async () => {
  1215. const permission = await IdleDetector.requestPermission();
  1216. resolve(permission);
  1217. });
  1218. button.click();
  1219. });
  1220. `, true);
  1221. expect(permission).to.eq('denied');
  1222. });
  1223. it('can allow the IdleDetector to start', async () => {
  1224. session.defaultSession.setPermissionCheckHandler((wc, permission) => {
  1225. return permission === 'idle-detection';
  1226. });
  1227. const w = new BrowserWindow({ show: false });
  1228. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1229. const result = await w.webContents.executeJavaScript(`
  1230. const detector = new IdleDetector({ threshold: 60000 });
  1231. detector.start().then(() => {
  1232. return 'success';
  1233. }).catch(e => e.message);
  1234. `, true);
  1235. expect(result).to.eq('success');
  1236. });
  1237. it('can prevent the IdleDetector from starting', async () => {
  1238. session.defaultSession.setPermissionCheckHandler((wc, permission) => {
  1239. return permission !== 'idle-detection';
  1240. });
  1241. const w = new BrowserWindow({ show: false });
  1242. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1243. const result = await w.webContents.executeJavaScript(`
  1244. const detector = new IdleDetector({ threshold: 60000 });
  1245. detector.start().then(() => {
  1246. console.log('success')
  1247. }).catch(e => e.message);
  1248. `, true);
  1249. expect(result).to.eq('Idle detection permission denied');
  1250. });
  1251. });
  1252. describe('navigator.mediaDevices', () => {
  1253. afterEach(closeAllWindows);
  1254. afterEach(() => {
  1255. session.defaultSession.setPermissionCheckHandler(null);
  1256. session.defaultSession.setPermissionRequestHandler(null);
  1257. });
  1258. it('can return labels of enumerated devices', async () => {
  1259. const w = new BrowserWindow({ show: false });
  1260. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1261. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  1262. expect(labels.some((l: any) => l)).to.be.true();
  1263. });
  1264. it('does not return labels of enumerated devices when permission denied', async () => {
  1265. session.defaultSession.setPermissionCheckHandler(() => false);
  1266. const w = new BrowserWindow({ show: false });
  1267. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1268. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  1269. expect(labels.some((l: any) => l)).to.be.false();
  1270. });
  1271. it('returns the same device ids across reloads', async () => {
  1272. const ses = session.fromPartition('persist:media-device-id');
  1273. const w = new BrowserWindow({
  1274. show: false,
  1275. webPreferences: {
  1276. nodeIntegration: true,
  1277. session: ses,
  1278. contextIsolation: false
  1279. }
  1280. });
  1281. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  1282. const [, firstDeviceIds] = await once(ipcMain, 'deviceIds');
  1283. w.webContents.reload();
  1284. const [, secondDeviceIds] = await once(ipcMain, 'deviceIds');
  1285. expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
  1286. });
  1287. it('can return new device id when cookie storage is cleared', async () => {
  1288. const ses = session.fromPartition('persist:media-device-id');
  1289. const w = new BrowserWindow({
  1290. show: false,
  1291. webPreferences: {
  1292. nodeIntegration: true,
  1293. session: ses,
  1294. contextIsolation: false
  1295. }
  1296. });
  1297. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  1298. const [, firstDeviceIds] = await once(ipcMain, 'deviceIds');
  1299. await ses.clearStorageData({ storages: ['cookies'] });
  1300. w.webContents.reload();
  1301. const [, secondDeviceIds] = await once(ipcMain, 'deviceIds');
  1302. expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
  1303. });
  1304. it('provides a securityOrigin to the request handler', async () => {
  1305. session.defaultSession.setPermissionRequestHandler(
  1306. (wc, permission, callback, details) => {
  1307. if (details.securityOrigin !== undefined) {
  1308. callback(true);
  1309. } else {
  1310. callback(false);
  1311. }
  1312. }
  1313. );
  1314. const w = new BrowserWindow({ show: false });
  1315. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1316. const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({
  1317. video: {
  1318. mandatory: {
  1319. chromeMediaSource: "desktop",
  1320. minWidth: 1280,
  1321. maxWidth: 1280,
  1322. minHeight: 720,
  1323. maxHeight: 720
  1324. }
  1325. }
  1326. }).then((stream) => stream.getVideoTracks())`);
  1327. expect(labels.some((l: any) => l)).to.be.true();
  1328. });
  1329. it('fails with "not supported" for getDisplayMedia', async () => {
  1330. const w = new BrowserWindow({ show: false });
  1331. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1332. const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true);
  1333. expect(ok).to.be.false();
  1334. expect(err).to.equal('Not supported');
  1335. });
  1336. });
  1337. describe('window.opener access', () => {
  1338. const scheme = 'app';
  1339. const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
  1340. const httpUrl1 = `${scheme}://origin1`;
  1341. const httpUrl2 = `${scheme}://origin2`;
  1342. const fileBlank = `file://${fixturesPath}/pages/blank.html`;
  1343. const httpBlank = `${scheme}://origin1/blank`;
  1344. const table = [
  1345. { parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false },
  1346. { parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false },
  1347. // {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open()
  1348. // {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open()
  1349. // NB. this is different from Chrome's behavior, which isolates file: urls from each other
  1350. { parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true },
  1351. { parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true },
  1352. { parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true },
  1353. { parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true },
  1354. { parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false },
  1355. { parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false }
  1356. ];
  1357. const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
  1358. before(() => {
  1359. protocol.registerFileProtocol(scheme, (request, callback) => {
  1360. if (request.url.includes('blank')) {
  1361. callback(`${fixturesPath}/pages/blank.html`);
  1362. } else {
  1363. callback(`${fixturesPath}/pages/window-opener-location.html`);
  1364. }
  1365. });
  1366. });
  1367. after(() => {
  1368. protocol.unregisterProtocol(scheme);
  1369. });
  1370. afterEach(closeAllWindows);
  1371. describe('when opened from main window', () => {
  1372. for (const { parent, child, nodeIntegration, openerAccessible } of table) {
  1373. for (const sandboxPopup of [false, true]) {
  1374. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  1375. it(description, async () => {
  1376. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1377. w.webContents.setWindowOpenHandler(() => ({
  1378. action: 'allow',
  1379. overrideBrowserWindowOptions: {
  1380. webPreferences: {
  1381. sandbox: sandboxPopup
  1382. }
  1383. }
  1384. }));
  1385. await w.loadURL(parent);
  1386. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
  1387. window.addEventListener('message', function f(e) {
  1388. resolve(e.data)
  1389. })
  1390. window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
  1391. })`);
  1392. if (openerAccessible) {
  1393. expect(childOpenerLocation).to.be.a('string');
  1394. } else {
  1395. expect(childOpenerLocation).to.be.null();
  1396. }
  1397. });
  1398. }
  1399. }
  1400. });
  1401. describe('when opened from <webview>', () => {
  1402. for (const { parent, child, nodeIntegration, openerAccessible } of table) {
  1403. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  1404. it(description, async () => {
  1405. // This test involves three contexts:
  1406. // 1. The root BrowserWindow in which the test is run,
  1407. // 2. A <webview> belonging to the root window,
  1408. // 3. A window opened by calling window.open() from within the <webview>.
  1409. // We are testing whether context (3) can access context (2) under various conditions.
  1410. // This is context (1), the base window for the test.
  1411. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
  1412. await w.loadURL('about:blank');
  1413. const parentCode = `new Promise((resolve) => {
  1414. // This is context (3), a child window of the WebView.
  1415. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes")
  1416. window.addEventListener("message", e => {
  1417. resolve(e.data)
  1418. })
  1419. })`;
  1420. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  1421. // This is context (2), a WebView which will call window.open()
  1422. const webview = new WebView()
  1423. webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
  1424. webview.setAttribute('webpreferences', 'contextIsolation=no')
  1425. webview.setAttribute('allowpopups', 'on')
  1426. webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
  1427. webview.addEventListener('dom-ready', async () => {
  1428. webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
  1429. })
  1430. document.body.appendChild(webview)
  1431. })`);
  1432. if (openerAccessible) {
  1433. expect(childOpenerLocation).to.be.a('string');
  1434. } else {
  1435. expect(childOpenerLocation).to.be.null();
  1436. }
  1437. });
  1438. }
  1439. });
  1440. });
  1441. describe('storage', () => {
  1442. describe('custom non standard schemes', () => {
  1443. const protocolName = 'storage';
  1444. let contents: WebContents;
  1445. before(() => {
  1446. protocol.registerFileProtocol(protocolName, (request, callback) => {
  1447. const parsedUrl = url.parse(request.url);
  1448. let filename;
  1449. switch (parsedUrl.pathname) {
  1450. case '/localStorage' : filename = 'local_storage.html'; break;
  1451. case '/sessionStorage' : filename = 'session_storage.html'; break;
  1452. case '/WebSQL' : filename = 'web_sql.html'; break;
  1453. case '/indexedDB' : filename = 'indexed_db.html'; break;
  1454. case '/cookie' : filename = 'cookie.html'; break;
  1455. default : filename = '';
  1456. }
  1457. callback({ path: `${fixturesPath}/pages/storage/${filename}` });
  1458. });
  1459. });
  1460. after(() => {
  1461. protocol.unregisterProtocol(protocolName);
  1462. });
  1463. beforeEach(() => {
  1464. contents = (webContents as typeof ElectronInternal.WebContents).create({
  1465. nodeIntegration: true,
  1466. contextIsolation: false
  1467. });
  1468. });
  1469. afterEach(() => {
  1470. contents.destroy();
  1471. contents = null as any;
  1472. });
  1473. it('cannot access localStorage', async () => {
  1474. const response = once(ipcMain, 'local-storage-response');
  1475. contents.loadURL(protocolName + '://host/localStorage');
  1476. const [, error] = await response;
  1477. expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.');
  1478. });
  1479. it('cannot access sessionStorage', async () => {
  1480. const response = once(ipcMain, 'session-storage-response');
  1481. contents.loadURL(`${protocolName}://host/sessionStorage`);
  1482. const [, error] = await response;
  1483. expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.');
  1484. });
  1485. it('cannot access WebSQL database', async () => {
  1486. const response = once(ipcMain, 'web-sql-response');
  1487. contents.loadURL(`${protocolName}://host/WebSQL`);
  1488. const [, error] = await response;
  1489. expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.');
  1490. });
  1491. it('cannot access indexedDB', async () => {
  1492. const response = once(ipcMain, 'indexed-db-response');
  1493. contents.loadURL(`${protocolName}://host/indexedDB`);
  1494. const [, error] = await response;
  1495. expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.');
  1496. });
  1497. it('cannot access cookie', async () => {
  1498. const response = once(ipcMain, 'cookie-response');
  1499. contents.loadURL(`${protocolName}://host/cookie`);
  1500. const [, error] = await response;
  1501. expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.');
  1502. });
  1503. });
  1504. describe('can be accessed', () => {
  1505. let server: http.Server;
  1506. let serverUrl: string;
  1507. let serverCrossSiteUrl: string;
  1508. before(async () => {
  1509. server = http.createServer((req, res) => {
  1510. const respond = () => {
  1511. if (req.url === '/redirect-cross-site') {
  1512. res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
  1513. res.statusCode = 302;
  1514. res.end();
  1515. } else if (req.url === '/redirected') {
  1516. res.end('<html><script>window.localStorage</script></html>');
  1517. } else {
  1518. res.end();
  1519. }
  1520. };
  1521. setTimeout().then(respond);
  1522. });
  1523. serverUrl = (await listen(server)).url;
  1524. serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
  1525. });
  1526. after(() => {
  1527. server.close();
  1528. server = null as any;
  1529. });
  1530. afterEach(closeAllWindows);
  1531. const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
  1532. it(testTitle, async () => {
  1533. const w = new BrowserWindow({
  1534. show: false,
  1535. ...extraPreferences
  1536. });
  1537. let redirected = false;
  1538. w.webContents.on('render-process-gone', () => {
  1539. expect.fail('renderer crashed / was killed');
  1540. });
  1541. w.webContents.on('did-redirect-navigation', (event, url) => {
  1542. expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
  1543. redirected = true;
  1544. });
  1545. await w.loadURL(`${serverUrl}/redirect-cross-site`);
  1546. expect(redirected).to.be.true('didnt redirect');
  1547. });
  1548. };
  1549. testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
  1550. testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
  1551. });
  1552. describe('enableWebSQL webpreference', () => {
  1553. const origin = `${standardScheme}://fake-host`;
  1554. const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
  1555. const sqlPartition = 'web-sql-preference-test';
  1556. const sqlSession = session.fromPartition(sqlPartition);
  1557. const securityError = 'An attempt was made to break through the security policy of the user agent.';
  1558. let contents: WebContents, w: BrowserWindow;
  1559. before(() => {
  1560. sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
  1561. callback({ path: filePath });
  1562. });
  1563. });
  1564. after(() => {
  1565. sqlSession.protocol.unregisterProtocol(standardScheme);
  1566. });
  1567. afterEach(async () => {
  1568. if (contents) {
  1569. contents.destroy();
  1570. contents = null as any;
  1571. }
  1572. await closeAllWindows();
  1573. (w as any) = null;
  1574. });
  1575. it('default value allows websql', async () => {
  1576. contents = (webContents as typeof ElectronInternal.WebContents).create({
  1577. session: sqlSession,
  1578. nodeIntegration: true,
  1579. contextIsolation: false
  1580. });
  1581. contents.loadURL(origin);
  1582. const [, error] = await once(ipcMain, 'web-sql-response');
  1583. expect(error).to.be.null();
  1584. });
  1585. it('when set to false can disallow websql', async () => {
  1586. contents = (webContents as typeof ElectronInternal.WebContents).create({
  1587. session: sqlSession,
  1588. nodeIntegration: true,
  1589. enableWebSQL: false,
  1590. contextIsolation: false
  1591. });
  1592. contents.loadURL(origin);
  1593. const [, error] = await once(ipcMain, 'web-sql-response');
  1594. expect(error).to.equal(securityError);
  1595. });
  1596. it('when set to false does not disable indexedDB', async () => {
  1597. contents = (webContents as typeof ElectronInternal.WebContents).create({
  1598. session: sqlSession,
  1599. nodeIntegration: true,
  1600. enableWebSQL: false,
  1601. contextIsolation: false
  1602. });
  1603. contents.loadURL(origin);
  1604. const [, error] = await once(ipcMain, 'web-sql-response');
  1605. expect(error).to.equal(securityError);
  1606. const dbName = 'random';
  1607. const result = await contents.executeJavaScript(`
  1608. new Promise((resolve, reject) => {
  1609. try {
  1610. let req = window.indexedDB.open('${dbName}');
  1611. req.onsuccess = (event) => {
  1612. let db = req.result;
  1613. resolve(db.name);
  1614. }
  1615. req.onerror = (event) => { resolve(event.target.code); }
  1616. } catch (e) {
  1617. resolve(e.message);
  1618. }
  1619. });
  1620. `);
  1621. expect(result).to.equal(dbName);
  1622. });
  1623. it('child webContents can override when the embedder has allowed websql', async () => {
  1624. w = new BrowserWindow({
  1625. show: false,
  1626. webPreferences: {
  1627. nodeIntegration: true,
  1628. webviewTag: true,
  1629. session: sqlSession,
  1630. contextIsolation: false
  1631. }
  1632. });
  1633. w.webContents.loadURL(origin);
  1634. const [, error] = await once(ipcMain, 'web-sql-response');
  1635. expect(error).to.be.null();
  1636. const webviewResult = once(ipcMain, 'web-sql-response');
  1637. await w.webContents.executeJavaScript(`
  1638. new Promise((resolve, reject) => {
  1639. const webview = new WebView();
  1640. webview.setAttribute('src', '${origin}');
  1641. webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no');
  1642. webview.setAttribute('partition', '${sqlPartition}');
  1643. webview.setAttribute('nodeIntegration', 'on');
  1644. document.body.appendChild(webview);
  1645. webview.addEventListener('dom-ready', () => resolve());
  1646. });
  1647. `);
  1648. const [, childError] = await webviewResult;
  1649. expect(childError).to.equal(securityError);
  1650. });
  1651. it('child webContents cannot override when the embedder has disallowed websql', async () => {
  1652. w = new BrowserWindow({
  1653. show: false,
  1654. webPreferences: {
  1655. nodeIntegration: true,
  1656. enableWebSQL: false,
  1657. webviewTag: true,
  1658. session: sqlSession,
  1659. contextIsolation: false
  1660. }
  1661. });
  1662. w.webContents.loadURL('data:text/html,<html></html>');
  1663. const webviewResult = once(ipcMain, 'web-sql-response');
  1664. await w.webContents.executeJavaScript(`
  1665. new Promise((resolve, reject) => {
  1666. const webview = new WebView();
  1667. webview.setAttribute('src', '${origin}');
  1668. webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
  1669. webview.setAttribute('partition', '${sqlPartition}');
  1670. webview.setAttribute('nodeIntegration', 'on');
  1671. document.body.appendChild(webview);
  1672. webview.addEventListener('dom-ready', () => resolve());
  1673. });
  1674. `);
  1675. const [, childError] = await webviewResult;
  1676. expect(childError).to.equal(securityError);
  1677. });
  1678. it('child webContents can use websql when the embedder has allowed websql', async () => {
  1679. w = new BrowserWindow({
  1680. show: false,
  1681. webPreferences: {
  1682. nodeIntegration: true,
  1683. webviewTag: true,
  1684. session: sqlSession,
  1685. contextIsolation: false
  1686. }
  1687. });
  1688. w.webContents.loadURL(origin);
  1689. const [, error] = await once(ipcMain, 'web-sql-response');
  1690. expect(error).to.be.null();
  1691. const webviewResult = once(ipcMain, 'web-sql-response');
  1692. await w.webContents.executeJavaScript(`
  1693. new Promise((resolve, reject) => {
  1694. const webview = new WebView();
  1695. webview.setAttribute('src', '${origin}');
  1696. webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
  1697. webview.setAttribute('partition', '${sqlPartition}');
  1698. webview.setAttribute('nodeIntegration', 'on');
  1699. document.body.appendChild(webview);
  1700. webview.addEventListener('dom-ready', () => resolve());
  1701. });
  1702. `);
  1703. const [, childError] = await webviewResult;
  1704. expect(childError).to.be.null();
  1705. });
  1706. });
  1707. describe('DOM storage quota increase', () => {
  1708. ['localStorage', 'sessionStorage'].forEach((storageName) => {
  1709. it(`allows saving at least 40MiB in ${storageName}`, async () => {
  1710. const w = new BrowserWindow({ show: false });
  1711. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1712. // Although JavaScript strings use UTF-16, the underlying
  1713. // storage provider may encode strings differently, muddling the
  1714. // translation between character and byte counts. However,
  1715. // a string of 40 * 2^20 characters will require at least 40MiB
  1716. // and presumably no more than 80MiB, a size guaranteed to
  1717. // to exceed the original 10MiB quota yet stay within the
  1718. // new 100MiB quota.
  1719. // Note that both the key name and value affect the total size.
  1720. const testKeyName = '_electronDOMStorageQuotaIncreasedTest';
  1721. const length = 40 * Math.pow(2, 20) - testKeyName.length;
  1722. await w.webContents.executeJavaScript(`
  1723. ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
  1724. `);
  1725. // Wait at least one turn of the event loop to help avoid false positives
  1726. // Although not entirely necessary, the previous version of this test case
  1727. // failed to detect a real problem (perhaps related to DOM storage data caching)
  1728. // wherein calling `getItem` immediately after `setItem` would appear to work
  1729. // but then later (e.g. next tick) it would not.
  1730. await setTimeout(1);
  1731. try {
  1732. const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`);
  1733. expect(storedLength).to.equal(length);
  1734. } finally {
  1735. await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
  1736. }
  1737. });
  1738. it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => {
  1739. const w = new BrowserWindow({ show: false });
  1740. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1741. await expect((async () => {
  1742. const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest';
  1743. const length = 128 * Math.pow(2, 20) - testKeyName.length;
  1744. try {
  1745. await w.webContents.executeJavaScript(`
  1746. ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
  1747. `);
  1748. } finally {
  1749. await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
  1750. }
  1751. })()).to.eventually.be.rejected();
  1752. });
  1753. });
  1754. });
  1755. describe('persistent storage', () => {
  1756. it('can be requested', async () => {
  1757. const w = new BrowserWindow({ show: false });
  1758. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1759. const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => {
  1760. navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve);
  1761. })`);
  1762. expect(grantedBytes).to.equal(1048576);
  1763. });
  1764. });
  1765. });
  1766. ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
  1767. const pdfSource = url.format({
  1768. pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'),
  1769. protocol: 'file',
  1770. slashes: true
  1771. });
  1772. it('successfully loads a PDF file', async () => {
  1773. const w = new BrowserWindow({ show: false });
  1774. w.loadURL(pdfSource);
  1775. await once(w.webContents, 'did-finish-load');
  1776. });
  1777. it('opens when loading a pdf resource as top level navigation', async () => {
  1778. const w = new BrowserWindow({ show: false });
  1779. w.loadURL(pdfSource);
  1780. const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
  1781. await once(contents, 'did-navigate');
  1782. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1783. });
  1784. it('opens when loading a pdf resource in a iframe', async () => {
  1785. const w = new BrowserWindow({ show: false });
  1786. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
  1787. const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
  1788. await once(contents, 'did-navigate');
  1789. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1790. });
  1791. });
  1792. describe('window.history', () => {
  1793. describe('window.history.pushState', () => {
  1794. it('should push state after calling history.pushState() from the same url', async () => {
  1795. const w = new BrowserWindow({ show: false });
  1796. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1797. // History should have current page by now.
  1798. expect((w.webContents as any).length()).to.equal(1);
  1799. const waitCommit = once(w.webContents, 'navigation-entry-committed');
  1800. w.webContents.executeJavaScript('window.history.pushState({}, "")');
  1801. await waitCommit;
  1802. // Initial page + pushed state.
  1803. expect((w.webContents as any).length()).to.equal(2);
  1804. });
  1805. });
  1806. describe('window.history.back', () => {
  1807. it('should not allow sandboxed iframe to modify main frame state', async () => {
  1808. const w = new BrowserWindow({ show: false });
  1809. w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>');
  1810. await Promise.all([
  1811. once(w.webContents, 'navigation-entry-committed'),
  1812. once(w.webContents, 'did-frame-navigate'),
  1813. once(w.webContents, 'did-navigate')
  1814. ]);
  1815. w.webContents.executeJavaScript('window.history.pushState(1, "")');
  1816. await Promise.all([
  1817. once(w.webContents, 'navigation-entry-committed'),
  1818. once(w.webContents, 'did-navigate-in-page')
  1819. ]);
  1820. (w.webContents as any).once('navigation-entry-committed', () => {
  1821. expect.fail('Unexpected navigation-entry-committed');
  1822. });
  1823. w.webContents.once('did-navigate-in-page', () => {
  1824. expect.fail('Unexpected did-navigate-in-page');
  1825. });
  1826. await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()');
  1827. expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1);
  1828. expect((w.webContents as any).getActiveIndex()).to.equal(1);
  1829. });
  1830. });
  1831. });
  1832. describe('chrome://media-internals', () => {
  1833. it('loads the page successfully', async () => {
  1834. const w = new BrowserWindow({ show: false });
  1835. w.loadURL('chrome://media-internals');
  1836. const pageExists = await w.webContents.executeJavaScript(
  1837. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1838. );
  1839. expect(pageExists).to.be.true();
  1840. });
  1841. });
  1842. describe('chrome://webrtc-internals', () => {
  1843. it('loads the page successfully', async () => {
  1844. const w = new BrowserWindow({ show: false });
  1845. w.loadURL('chrome://webrtc-internals');
  1846. const pageExists = await w.webContents.executeJavaScript(
  1847. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1848. );
  1849. expect(pageExists).to.be.true();
  1850. });
  1851. });
  1852. describe('document.hasFocus', () => {
  1853. it('has correct value when multiple windows are opened', async () => {
  1854. const w1 = new BrowserWindow({ show: true });
  1855. const w2 = new BrowserWindow({ show: true });
  1856. const w3 = new BrowserWindow({ show: false });
  1857. await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1858. await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1859. await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1860. expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id);
  1861. let focus = false;
  1862. focus = await w1.webContents.executeJavaScript(
  1863. 'document.hasFocus()'
  1864. );
  1865. expect(focus).to.be.false();
  1866. focus = await w2.webContents.executeJavaScript(
  1867. 'document.hasFocus()'
  1868. );
  1869. expect(focus).to.be.true();
  1870. focus = await w3.webContents.executeJavaScript(
  1871. 'document.hasFocus()'
  1872. );
  1873. expect(focus).to.be.false();
  1874. });
  1875. });
  1876. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation
  1877. describe('navigator.connection', () => {
  1878. it('returns the correct value', async () => {
  1879. const w = new BrowserWindow({ show: false });
  1880. w.webContents.session.enableNetworkEmulation({
  1881. latency: 500,
  1882. downloadThroughput: 6400,
  1883. uploadThroughput: 6400
  1884. });
  1885. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1886. const rtt = await w.webContents.executeJavaScript('navigator.connection.rtt');
  1887. expect(rtt).to.be.a('number');
  1888. const downlink = await w.webContents.executeJavaScript('navigator.connection.downlink');
  1889. expect(downlink).to.be.a('number');
  1890. const effectiveTypes = ['slow-2g', '2g', '3g', '4g'];
  1891. const effectiveType = await w.webContents.executeJavaScript('navigator.connection.effectiveType');
  1892. expect(effectiveTypes).to.include(effectiveType);
  1893. });
  1894. });
  1895. describe('navigator.userAgentData', () => {
  1896. // These tests are done on an http server because navigator.userAgentData
  1897. // requires a secure context.
  1898. let server: http.Server;
  1899. let serverUrl: string;
  1900. before(async () => {
  1901. server = http.createServer((req, res) => {
  1902. res.setHeader('Content-Type', 'text/html');
  1903. res.end('');
  1904. });
  1905. serverUrl = (await listen(server)).url;
  1906. });
  1907. after(() => {
  1908. server.close();
  1909. });
  1910. describe('is not empty', () => {
  1911. it('by default', async () => {
  1912. const w = new BrowserWindow({ show: false });
  1913. await w.loadURL(serverUrl);
  1914. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1915. expect(platform).not.to.be.empty();
  1916. });
  1917. it('when there is a session-wide UA override', async () => {
  1918. const ses = session.fromPartition(`${Math.random()}`);
  1919. ses.setUserAgent('foobar');
  1920. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  1921. await w.loadURL(serverUrl);
  1922. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1923. expect(platform).not.to.be.empty();
  1924. });
  1925. it('when there is a WebContents-specific UA override', async () => {
  1926. const w = new BrowserWindow({ show: false });
  1927. w.webContents.setUserAgent('foo');
  1928. await w.loadURL(serverUrl);
  1929. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1930. expect(platform).not.to.be.empty();
  1931. });
  1932. it('when there is a WebContents-specific UA override at load time', async () => {
  1933. const w = new BrowserWindow({ show: false });
  1934. await w.loadURL(serverUrl, {
  1935. userAgent: 'foo'
  1936. });
  1937. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1938. expect(platform).not.to.be.empty();
  1939. });
  1940. });
  1941. describe('brand list', () => {
  1942. it('contains chromium', async () => {
  1943. const w = new BrowserWindow({ show: false });
  1944. await w.loadURL(serverUrl);
  1945. const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands');
  1946. expect(brands.map((b: any) => b.brand)).to.include('Chromium');
  1947. });
  1948. });
  1949. });
  1950. describe('Badging API', () => {
  1951. it('does not crash', async () => {
  1952. const w = new BrowserWindow({ show: false });
  1953. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1954. await w.webContents.executeJavaScript('navigator.setAppBadge(42)');
  1955. await w.webContents.executeJavaScript('navigator.setAppBadge()');
  1956. await w.webContents.executeJavaScript('navigator.clearAppBadge()');
  1957. });
  1958. });
  1959. describe('navigator.webkitGetUserMedia', () => {
  1960. it('calls its callbacks', async () => {
  1961. const w = new BrowserWindow({ show: false });
  1962. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1963. await w.webContents.executeJavaScript(`new Promise((resolve) => {
  1964. navigator.webkitGetUserMedia({
  1965. audio: true,
  1966. video: false
  1967. }, () => resolve(),
  1968. () => resolve());
  1969. })`);
  1970. });
  1971. });
  1972. describe('navigator.language', () => {
  1973. it('should not be empty', async () => {
  1974. const w = new BrowserWindow({ show: false });
  1975. await w.loadURL('about:blank');
  1976. expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal('');
  1977. });
  1978. });
  1979. describe('heap snapshot', () => {
  1980. it('does not crash', async () => {
  1981. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1982. w.loadURL('about:blank');
  1983. await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()');
  1984. });
  1985. });
  1986. // This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761
  1987. ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => {
  1988. it('can be gotten as context in canvas', async () => {
  1989. const w = new BrowserWindow({ show: false });
  1990. w.loadURL('about:blank');
  1991. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1992. const canWebglContextBeCreated = await w.webContents.executeJavaScript(`
  1993. document.createElement('canvas').getContext('webgl') != null;
  1994. `);
  1995. expect(canWebglContextBeCreated).to.be.true();
  1996. });
  1997. });
  1998. describe('iframe', () => {
  1999. it('does not have node integration', async () => {
  2000. const w = new BrowserWindow({ show: false });
  2001. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  2002. const result = await w.webContents.executeJavaScript(`
  2003. const iframe = document.createElement('iframe')
  2004. iframe.src = './set-global.html';
  2005. document.body.appendChild(iframe);
  2006. new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test))
  2007. `);
  2008. expect(result).to.equal('undefined undefined undefined');
  2009. });
  2010. });
  2011. describe('websockets', () => {
  2012. it('has user agent', async () => {
  2013. const server = http.createServer();
  2014. const { port } = await listen(server);
  2015. const wss = new ws.Server({ server: server });
  2016. const finished = new Promise<string | undefined>((resolve, reject) => {
  2017. wss.on('error', reject);
  2018. wss.on('connection', (ws, upgradeReq) => {
  2019. resolve(upgradeReq.headers['user-agent']);
  2020. });
  2021. });
  2022. const w = new BrowserWindow({ show: false });
  2023. w.loadURL('about:blank');
  2024. w.webContents.executeJavaScript(`
  2025. new WebSocket('ws://127.0.0.1:${port}');
  2026. `);
  2027. expect(await finished).to.include('Electron');
  2028. });
  2029. });
  2030. describe('fetch', () => {
  2031. it('does not crash', async () => {
  2032. const server = http.createServer((req, res) => {
  2033. res.end('test');
  2034. });
  2035. defer(() => server.close());
  2036. const { port } = await listen(server);
  2037. const w = new BrowserWindow({ show: false });
  2038. w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  2039. const x = await w.webContents.executeJavaScript(`
  2040. fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader())
  2041. .then((reader) => {
  2042. return reader.read().then((r) => {
  2043. reader.cancel();
  2044. return r.value;
  2045. });
  2046. })
  2047. `);
  2048. expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116]));
  2049. });
  2050. });
  2051. describe('Promise', () => {
  2052. before(() => {
  2053. ipcMain.handle('ping', (e, arg) => arg);
  2054. });
  2055. after(() => {
  2056. ipcMain.removeHandler('ping');
  2057. });
  2058. itremote('resolves correctly in Node.js calls', async () => {
  2059. await new Promise<void>((resolve, reject) => {
  2060. class XElement extends HTMLElement {}
  2061. customElements.define('x-element', XElement);
  2062. setImmediate(() => {
  2063. let called = false;
  2064. Promise.resolve().then(() => {
  2065. if (called) resolve();
  2066. else reject(new Error('wrong sequence'));
  2067. });
  2068. document.createElement('x-element');
  2069. called = true;
  2070. });
  2071. });
  2072. });
  2073. itremote('resolves correctly in Electron calls', async () => {
  2074. await new Promise<void>((resolve, reject) => {
  2075. class YElement extends HTMLElement {}
  2076. customElements.define('y-element', YElement);
  2077. require('electron').ipcRenderer.invoke('ping').then(() => {
  2078. let called = false;
  2079. Promise.resolve().then(() => {
  2080. if (called) resolve();
  2081. else reject(new Error('wrong sequence'));
  2082. });
  2083. document.createElement('y-element');
  2084. called = true;
  2085. });
  2086. });
  2087. });
  2088. });
  2089. describe('synchronous prompts', () => {
  2090. describe('window.alert(message, title)', () => {
  2091. itremote('throws an exception when the arguments cannot be converted to strings', () => {
  2092. expect(() => {
  2093. window.alert({ toString: null });
  2094. }).to.throw('Cannot convert object to primitive value');
  2095. });
  2096. });
  2097. describe('window.confirm(message, title)', () => {
  2098. itremote('throws an exception when the arguments cannot be converted to strings', () => {
  2099. expect(() => {
  2100. (window.confirm as any)({ toString: null }, 'title');
  2101. }).to.throw('Cannot convert object to primitive value');
  2102. });
  2103. });
  2104. });
  2105. describe('window.history', () => {
  2106. describe('window.history.go(offset)', () => {
  2107. itremote('throws an exception when the argument cannot be converted to a string', () => {
  2108. expect(() => {
  2109. (window.history.go as any)({ toString: null });
  2110. }).to.throw('Cannot convert object to primitive value');
  2111. });
  2112. });
  2113. });
  2114. describe('console functions', () => {
  2115. itremote('should exist', () => {
  2116. expect(console.log, 'log').to.be.a('function');
  2117. expect(console.error, 'error').to.be.a('function');
  2118. expect(console.warn, 'warn').to.be.a('function');
  2119. expect(console.info, 'info').to.be.a('function');
  2120. expect(console.debug, 'debug').to.be.a('function');
  2121. expect(console.trace, 'trace').to.be.a('function');
  2122. expect(console.time, 'time').to.be.a('function');
  2123. expect(console.timeEnd, 'timeEnd').to.be.a('function');
  2124. });
  2125. });
  2126. // FIXME(nornagon): this is broken on CI, it triggers:
  2127. // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will
  2128. // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side
  2129. // (null text in SpeechSynthesisUtterance struct).
  2130. describe('SpeechSynthesis', () => {
  2131. itremote('should emit lifecycle events', async () => {
  2132. const sentence = `long sentence which will take at least a few seconds to
  2133. utter so that it's possible to pause and resume before the end`;
  2134. const utter = new SpeechSynthesisUtterance(sentence);
  2135. // Create a dummy utterance so that speech synthesis state
  2136. // is initialized for later calls.
  2137. speechSynthesis.speak(new SpeechSynthesisUtterance());
  2138. speechSynthesis.cancel();
  2139. speechSynthesis.speak(utter);
  2140. // paused state after speak()
  2141. expect(speechSynthesis.paused).to.be.false();
  2142. await new Promise((resolve) => { utter.onstart = resolve; });
  2143. // paused state after start event
  2144. expect(speechSynthesis.paused).to.be.false();
  2145. speechSynthesis.pause();
  2146. // paused state changes async, right before the pause event
  2147. expect(speechSynthesis.paused).to.be.false();
  2148. await new Promise((resolve) => { utter.onpause = resolve; });
  2149. expect(speechSynthesis.paused).to.be.true();
  2150. speechSynthesis.resume();
  2151. await new Promise((resolve) => { utter.onresume = resolve; });
  2152. // paused state after resume event
  2153. expect(speechSynthesis.paused).to.be.false();
  2154. await new Promise((resolve) => { utter.onend = resolve; });
  2155. });
  2156. });
  2157. });
  2158. describe('font fallback', () => {
  2159. async function getRenderedFonts (html: string) {
  2160. const w = new BrowserWindow({ show: false });
  2161. try {
  2162. await w.loadURL(`data:text/html,${html}`);
  2163. w.webContents.debugger.attach();
  2164. const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
  2165. const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
  2166. await sendCommand('CSS.enable');
  2167. const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
  2168. return fonts;
  2169. } finally {
  2170. w.close();
  2171. }
  2172. }
  2173. it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
  2174. const html = '<body style="font-family: sans-serif">test</body>';
  2175. const fonts = await getRenderedFonts(html);
  2176. expect(fonts).to.be.an('array');
  2177. expect(fonts).to.have.length(1);
  2178. if (process.platform === 'win32') {
  2179. expect(fonts[0].familyName).to.equal('Arial');
  2180. } else if (process.platform === 'darwin') {
  2181. expect(fonts[0].familyName).to.equal('Helvetica');
  2182. } else if (process.platform === 'linux') {
  2183. expect(fonts[0].familyName).to.equal('DejaVu Sans');
  2184. } // I think this depends on the distro? We don't specify a default.
  2185. });
  2186. ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
  2187. const html = `
  2188. <html lang="ja-JP">
  2189. <head>
  2190. <meta charset="utf-8" />
  2191. </head>
  2192. <body style="font-family: sans-serif">test 智史</body>
  2193. </html>
  2194. `;
  2195. const fonts = await getRenderedFonts(html);
  2196. expect(fonts).to.be.an('array');
  2197. expect(fonts).to.have.length(1);
  2198. 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'); }
  2199. });
  2200. });
  2201. describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
  2202. const fullscreenChildHtml = promisify(fs.readFile)(
  2203. path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
  2204. );
  2205. let w: BrowserWindow;
  2206. let server: http.Server;
  2207. let crossSiteUrl: string;
  2208. beforeEach(async () => {
  2209. server = http.createServer(async (_req, res) => {
  2210. res.writeHead(200, { 'Content-Type': 'text/html' });
  2211. res.write(await fullscreenChildHtml);
  2212. res.end();
  2213. });
  2214. const serverUrl = (await listen(server)).url;
  2215. crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
  2216. w = new BrowserWindow({
  2217. show: true,
  2218. fullscreen: true,
  2219. webPreferences: {
  2220. nodeIntegration: true,
  2221. nodeIntegrationInSubFrames: true,
  2222. contextIsolation: false
  2223. }
  2224. });
  2225. });
  2226. afterEach(async () => {
  2227. await closeAllWindows();
  2228. (w as any) = null;
  2229. server.close();
  2230. });
  2231. ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => {
  2232. const fullscreenChange = once(ipcMain, 'fullscreenChange');
  2233. const html =
  2234. `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
  2235. w.loadURL(`data:text/html,${html}`);
  2236. await fullscreenChange;
  2237. const fullscreenWidth = await w.webContents.executeJavaScript(
  2238. "document.querySelector('iframe').offsetWidth"
  2239. );
  2240. expect(fullscreenWidth > 0).to.be.true();
  2241. await w.webContents.executeJavaScript(
  2242. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  2243. );
  2244. await setTimeout(500);
  2245. const width = await w.webContents.executeJavaScript(
  2246. "document.querySelector('iframe').offsetWidth"
  2247. );
  2248. expect(width).to.equal(0);
  2249. });
  2250. ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => {
  2251. await once(w, 'enter-full-screen');
  2252. const fullscreenChange = once(ipcMain, 'fullscreenChange');
  2253. const html =
  2254. `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
  2255. w.loadURL(`data:text/html,${html}`);
  2256. await fullscreenChange;
  2257. const fullscreenWidth = await w.webContents.executeJavaScript(
  2258. "document.querySelector('iframe').offsetWidth"
  2259. );
  2260. expect(fullscreenWidth > 0).to.be.true();
  2261. await w.webContents.executeJavaScript(
  2262. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  2263. );
  2264. await once(w.webContents, 'leave-html-full-screen');
  2265. const width = await w.webContents.executeJavaScript(
  2266. "document.querySelector('iframe').offsetWidth"
  2267. );
  2268. expect(width).to.equal(0);
  2269. w.setFullScreen(false);
  2270. await once(w, 'leave-full-screen');
  2271. });
  2272. // TODO(jkleinsc) fix this flaky test on WOA
  2273. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => {
  2274. if (process.platform === 'darwin') await once(w, 'enter-full-screen');
  2275. const fullscreenChange = once(ipcMain, 'fullscreenChange');
  2276. w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
  2277. await fullscreenChange;
  2278. const fullscreenWidth = await w.webContents.executeJavaScript(
  2279. "document.querySelector('iframe').offsetWidth"
  2280. );
  2281. expect(fullscreenWidth > 0).to.true();
  2282. await w.webContents.executeJavaScript('document.exitFullscreen()');
  2283. const width = await w.webContents.executeJavaScript(
  2284. "document.querySelector('iframe').offsetWidth"
  2285. );
  2286. expect(width).to.equal(0);
  2287. });
  2288. });
  2289. describe('navigator.serial', () => {
  2290. let w: BrowserWindow;
  2291. before(async () => {
  2292. w = new BrowserWindow({
  2293. show: false
  2294. });
  2295. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2296. });
  2297. const getPorts: any = () => {
  2298. return w.webContents.executeJavaScript(`
  2299. navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
  2300. `, true);
  2301. };
  2302. const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.';
  2303. after(closeAllWindows);
  2304. afterEach(() => {
  2305. session.defaultSession.setPermissionCheckHandler(null);
  2306. session.defaultSession.removeAllListeners('select-serial-port');
  2307. });
  2308. it('does not return a port if select-serial-port event is not defined', async () => {
  2309. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2310. const port = await getPorts();
  2311. expect(port).to.equal(notFoundError);
  2312. });
  2313. it('does not return a port when permission denied', async () => {
  2314. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2315. callback(portList[0].portId);
  2316. });
  2317. session.defaultSession.setPermissionCheckHandler(() => false);
  2318. const port = await getPorts();
  2319. expect(port).to.equal(notFoundError);
  2320. });
  2321. it('does not crash when select-serial-port is called with an invalid port', async () => {
  2322. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2323. callback('i-do-not-exist');
  2324. });
  2325. const port = await getPorts();
  2326. expect(port).to.equal(notFoundError);
  2327. });
  2328. it('returns a port when select-serial-port event is defined', async () => {
  2329. let havePorts = false;
  2330. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2331. if (portList.length > 0) {
  2332. havePorts = true;
  2333. callback(portList[0].portId);
  2334. } else {
  2335. callback('');
  2336. }
  2337. });
  2338. const port = await getPorts();
  2339. if (havePorts) {
  2340. expect(port).to.equal('[object SerialPort]');
  2341. } else {
  2342. expect(port).to.equal(notFoundError);
  2343. }
  2344. });
  2345. it('navigator.serial.getPorts() returns values', async () => {
  2346. let havePorts = false;
  2347. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2348. if (portList.length > 0) {
  2349. havePorts = true;
  2350. callback(portList[0].portId);
  2351. } else {
  2352. callback('');
  2353. }
  2354. });
  2355. await getPorts();
  2356. if (havePorts) {
  2357. const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
  2358. expect(grantedPorts).to.not.be.empty();
  2359. }
  2360. });
  2361. it('supports port.forget()', async () => {
  2362. let forgottenPortFromEvent = {};
  2363. let havePorts = false;
  2364. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2365. if (portList.length > 0) {
  2366. havePorts = true;
  2367. callback(portList[0].portId);
  2368. } else {
  2369. callback('');
  2370. }
  2371. });
  2372. w.webContents.session.on('serial-port-revoked', (event, details) => {
  2373. forgottenPortFromEvent = details.port;
  2374. });
  2375. await getPorts();
  2376. if (havePorts) {
  2377. const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
  2378. if (grantedPorts.length > 0) {
  2379. const forgottenPort = await w.webContents.executeJavaScript(`
  2380. navigator.serial.getPorts().then(async(ports) => {
  2381. const portInfo = await ports[0].getInfo();
  2382. await ports[0].forget();
  2383. if (portInfo.usbVendorId && portInfo.usbProductId) {
  2384. return {
  2385. vendorId: '' + portInfo.usbVendorId,
  2386. productId: '' + portInfo.usbProductId
  2387. }
  2388. } else {
  2389. return {};
  2390. }
  2391. })
  2392. `);
  2393. const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
  2394. expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length);
  2395. if (forgottenPort.vendorId && forgottenPort.productId) {
  2396. expect(forgottenPortFromEvent).to.include(forgottenPort);
  2397. }
  2398. }
  2399. }
  2400. });
  2401. });
  2402. describe('window.getScreenDetails', () => {
  2403. let w: BrowserWindow;
  2404. before(async () => {
  2405. w = new BrowserWindow({
  2406. show: false
  2407. });
  2408. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2409. });
  2410. after(closeAllWindows);
  2411. afterEach(() => {
  2412. session.defaultSession.setPermissionRequestHandler(null);
  2413. });
  2414. const getScreenDetails: any = () => {
  2415. return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true);
  2416. };
  2417. it('returns screens when a PermissionRequestHandler is not defined', async () => {
  2418. const screens = await getScreenDetails();
  2419. expect(screens).to.not.equal('Read permission denied.');
  2420. });
  2421. it('returns an error when permission denied', async () => {
  2422. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2423. if (permission === 'window-management') {
  2424. callback(false);
  2425. } else {
  2426. callback(true);
  2427. }
  2428. });
  2429. const screens = await getScreenDetails();
  2430. expect(screens).to.equal('Permission denied.');
  2431. });
  2432. it('returns screens when permission is granted', async () => {
  2433. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2434. if (permission === 'window-management') {
  2435. callback(true);
  2436. } else {
  2437. callback(false);
  2438. }
  2439. });
  2440. const screens = await getScreenDetails();
  2441. expect(screens).to.not.equal('Permission denied.');
  2442. });
  2443. });
  2444. describe('navigator.clipboard.read', () => {
  2445. let w: BrowserWindow;
  2446. before(async () => {
  2447. w = new BrowserWindow();
  2448. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2449. });
  2450. const readClipboard: any = () => {
  2451. return w.webContents.executeJavaScript(`
  2452. navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
  2453. `, true);
  2454. };
  2455. after(closeAllWindows);
  2456. afterEach(() => {
  2457. session.defaultSession.setPermissionRequestHandler(null);
  2458. });
  2459. it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
  2460. const clipboard = await readClipboard();
  2461. expect(clipboard).to.not.equal('Read permission denied.');
  2462. });
  2463. it('returns an error when permission denied', async () => {
  2464. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2465. if (permission === 'clipboard-read') {
  2466. callback(false);
  2467. } else {
  2468. callback(true);
  2469. }
  2470. });
  2471. const clipboard = await readClipboard();
  2472. expect(clipboard).to.equal('Read permission denied.');
  2473. });
  2474. it('returns clipboard contents when permission is granted', async () => {
  2475. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2476. if (permission === 'clipboard-read') {
  2477. callback(true);
  2478. } else {
  2479. callback(false);
  2480. }
  2481. });
  2482. const clipboard = await readClipboard();
  2483. expect(clipboard).to.not.equal('Read permission denied.');
  2484. });
  2485. });
  2486. describe('navigator.clipboard.write', () => {
  2487. let w: BrowserWindow;
  2488. before(async () => {
  2489. w = new BrowserWindow();
  2490. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2491. });
  2492. const writeClipboard: any = () => {
  2493. return w.webContents.executeJavaScript(`
  2494. navigator.clipboard.writeText('Hello World!').catch(err => err.message);
  2495. `, true);
  2496. };
  2497. after(closeAllWindows);
  2498. afterEach(() => {
  2499. session.defaultSession.setPermissionRequestHandler(null);
  2500. });
  2501. it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
  2502. const clipboard = await writeClipboard();
  2503. expect(clipboard).to.not.equal('Write permission denied.');
  2504. });
  2505. it('returns an error when permission denied', async () => {
  2506. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2507. if (permission === 'clipboard-sanitized-write') {
  2508. callback(false);
  2509. } else {
  2510. callback(true);
  2511. }
  2512. });
  2513. const clipboard = await writeClipboard();
  2514. expect(clipboard).to.equal('Write permission denied.');
  2515. });
  2516. it('returns clipboard contents when permission is granted', async () => {
  2517. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2518. if (permission === 'clipboard-sanitized-write') {
  2519. callback(true);
  2520. } else {
  2521. callback(false);
  2522. }
  2523. });
  2524. const clipboard = await writeClipboard();
  2525. expect(clipboard).to.not.equal('Write permission denied.');
  2526. });
  2527. });
  2528. ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
  2529. let w: BrowserWindow;
  2530. const expectedBadgeCount = 42;
  2531. const fireAppBadgeAction: any = (action: string, value: any) => {
  2532. return w.webContents.executeJavaScript(`
  2533. navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
  2534. };
  2535. // For some reason on macOS changing the badge count doesn't happen right away, so wait
  2536. // until it changes.
  2537. async function waitForBadgeCount (value: number) {
  2538. let badgeCount = app.getBadgeCount();
  2539. while (badgeCount !== value) {
  2540. await setTimeout(10);
  2541. badgeCount = app.getBadgeCount();
  2542. }
  2543. return badgeCount;
  2544. }
  2545. describe('in the renderer', () => {
  2546. before(async () => {
  2547. w = new BrowserWindow({
  2548. show: false
  2549. });
  2550. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2551. });
  2552. after(() => {
  2553. app.badgeCount = 0;
  2554. closeAllWindows();
  2555. });
  2556. it('setAppBadge can set a numerical value', async () => {
  2557. const result = await fireAppBadgeAction('set', expectedBadgeCount);
  2558. expect(result).to.equal('success');
  2559. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2560. });
  2561. it('setAppBadge can set an empty(dot) value', async () => {
  2562. const result = await fireAppBadgeAction('set');
  2563. expect(result).to.equal('success');
  2564. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  2565. });
  2566. it('clearAppBadge can clear a value', async () => {
  2567. let result = await fireAppBadgeAction('set', expectedBadgeCount);
  2568. expect(result).to.equal('success');
  2569. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2570. result = await fireAppBadgeAction('clear');
  2571. expect(result).to.equal('success');
  2572. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  2573. });
  2574. });
  2575. describe('in a service worker', () => {
  2576. beforeEach(async () => {
  2577. w = new BrowserWindow({
  2578. show: false,
  2579. webPreferences: {
  2580. nodeIntegration: true,
  2581. partition: 'sw-file-scheme-spec',
  2582. contextIsolation: false
  2583. }
  2584. });
  2585. });
  2586. afterEach(() => {
  2587. app.badgeCount = 0;
  2588. closeAllWindows();
  2589. });
  2590. it('setAppBadge can be called in a ServiceWorker', (done) => {
  2591. w.webContents.on('ipc-message', (event, channel, message) => {
  2592. if (channel === 'reload') {
  2593. w.webContents.reload();
  2594. } else if (channel === 'error') {
  2595. done(message);
  2596. } else if (channel === 'response') {
  2597. expect(message).to.equal('SUCCESS setting app badge');
  2598. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2599. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  2600. storages: ['serviceworkers']
  2601. }).then(() => done());
  2602. }
  2603. });
  2604. w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
  2605. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
  2606. });
  2607. it('clearAppBadge can be called in a ServiceWorker', (done) => {
  2608. w.webContents.on('ipc-message', (event, channel, message) => {
  2609. if (channel === 'reload') {
  2610. w.webContents.reload();
  2611. } else if (channel === 'setAppBadge') {
  2612. expect(message).to.equal('SUCCESS setting app badge');
  2613. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2614. } else if (channel === 'error') {
  2615. done(message);
  2616. } else if (channel === 'response') {
  2617. expect(message).to.equal('SUCCESS clearing app badge');
  2618. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2619. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  2620. storages: ['serviceworkers']
  2621. }).then(() => done());
  2622. }
  2623. });
  2624. w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
  2625. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
  2626. });
  2627. });
  2628. });
  2629. describe('navigator.bluetooth', () => {
  2630. let w: BrowserWindow;
  2631. before(async () => {
  2632. w = new BrowserWindow({
  2633. show: false,
  2634. webPreferences: {
  2635. enableBlinkFeatures: 'WebBluetooth'
  2636. }
  2637. });
  2638. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2639. });
  2640. after(closeAllWindows);
  2641. it('can request bluetooth devices', async () => {
  2642. const bluetooth = await w.webContents.executeJavaScript(`
  2643. navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
  2644. expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
  2645. });
  2646. });
  2647. describe('navigator.hid', () => {
  2648. let w: BrowserWindow;
  2649. let server: http.Server;
  2650. let serverUrl: string;
  2651. before(async () => {
  2652. w = new BrowserWindow({
  2653. show: false
  2654. });
  2655. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2656. server = http.createServer((req, res) => {
  2657. res.setHeader('Content-Type', 'text/html');
  2658. res.end('<body>');
  2659. });
  2660. serverUrl = (await listen(server)).url;
  2661. });
  2662. const requestDevices: any = () => {
  2663. return w.webContents.executeJavaScript(`
  2664. navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
  2665. `, true);
  2666. };
  2667. after(() => {
  2668. server.close();
  2669. closeAllWindows();
  2670. });
  2671. afterEach(() => {
  2672. session.defaultSession.setPermissionCheckHandler(null);
  2673. session.defaultSession.setDevicePermissionHandler(null);
  2674. session.defaultSession.removeAllListeners('select-hid-device');
  2675. });
  2676. it('does not return a device if select-hid-device event is not defined', async () => {
  2677. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2678. const device = await requestDevices();
  2679. expect(device).to.equal('');
  2680. });
  2681. it('does not return a device when permission denied', async () => {
  2682. let selectFired = false;
  2683. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2684. selectFired = true;
  2685. callback();
  2686. });
  2687. session.defaultSession.setPermissionCheckHandler(() => false);
  2688. const device = await requestDevices();
  2689. expect(selectFired).to.be.false();
  2690. expect(device).to.equal('');
  2691. });
  2692. it('returns a device when select-hid-device event is defined', async () => {
  2693. let haveDevices = false;
  2694. let selectFired = false;
  2695. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2696. expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
  2697. selectFired = true;
  2698. if (details.deviceList.length > 0) {
  2699. haveDevices = true;
  2700. callback(details.deviceList[0].deviceId);
  2701. } else {
  2702. callback();
  2703. }
  2704. });
  2705. const device = await requestDevices();
  2706. expect(selectFired).to.be.true();
  2707. if (haveDevices) {
  2708. expect(device).to.contain('[object HIDDevice]');
  2709. } else {
  2710. expect(device).to.equal('');
  2711. }
  2712. if (haveDevices) {
  2713. // Verify that navigation will clear device permissions
  2714. const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  2715. expect(grantedDevices).to.not.be.empty();
  2716. w.loadURL(serverUrl);
  2717. const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
  2718. const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
  2719. expect(!!frame).to.be.true();
  2720. if (frame) {
  2721. const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
  2722. expect(grantedDevicesOnNewPage).to.be.empty();
  2723. }
  2724. }
  2725. });
  2726. it('returns a device when DevicePermissionHandler is defined', async () => {
  2727. let haveDevices = false;
  2728. let selectFired = false;
  2729. let gotDevicePerms = false;
  2730. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2731. selectFired = true;
  2732. if (details.deviceList.length > 0) {
  2733. const foundDevice = details.deviceList.find((device) => {
  2734. if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
  2735. haveDevices = true;
  2736. return true;
  2737. }
  2738. });
  2739. if (foundDevice) {
  2740. callback(foundDevice.deviceId);
  2741. return;
  2742. }
  2743. }
  2744. callback();
  2745. });
  2746. session.defaultSession.setDevicePermissionHandler(() => {
  2747. gotDevicePerms = true;
  2748. return true;
  2749. });
  2750. await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
  2751. const device = await requestDevices();
  2752. expect(selectFired).to.be.true();
  2753. if (haveDevices) {
  2754. expect(device).to.contain('[object HIDDevice]');
  2755. expect(gotDevicePerms).to.be.true();
  2756. } else {
  2757. expect(device).to.equal('');
  2758. }
  2759. });
  2760. it('excludes a device when a exclusionFilter is specified', async () => {
  2761. const exclusionFilters = <any>[];
  2762. let haveDevices = false;
  2763. let checkForExcludedDevice = false;
  2764. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2765. if (details.deviceList.length > 0) {
  2766. details.deviceList.find((device) => {
  2767. if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
  2768. if (checkForExcludedDevice) {
  2769. const compareDevice = {
  2770. vendorId: device.vendorId,
  2771. productId: device.productId
  2772. };
  2773. expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned');
  2774. } else {
  2775. haveDevices = true;
  2776. exclusionFilters.push({
  2777. vendorId: device.vendorId,
  2778. productId: device.productId
  2779. });
  2780. return true;
  2781. }
  2782. }
  2783. });
  2784. }
  2785. callback();
  2786. });
  2787. await requestDevices();
  2788. if (haveDevices) {
  2789. // We have devices to exclude, so check if exclusionFilters work
  2790. checkForExcludedDevice = true;
  2791. await w.webContents.executeJavaScript(`
  2792. navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString());
  2793. `, true);
  2794. }
  2795. });
  2796. it('supports device.forget()', async () => {
  2797. let deletedDeviceFromEvent;
  2798. let haveDevices = false;
  2799. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2800. if (details.deviceList.length > 0) {
  2801. haveDevices = true;
  2802. callback(details.deviceList[0].deviceId);
  2803. } else {
  2804. callback();
  2805. }
  2806. });
  2807. w.webContents.session.on('hid-device-revoked', (event, details) => {
  2808. deletedDeviceFromEvent = details.device;
  2809. });
  2810. await requestDevices();
  2811. if (haveDevices) {
  2812. const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  2813. if (grantedDevices.length > 0) {
  2814. const deletedDevice = await w.webContents.executeJavaScript(`
  2815. navigator.hid.getDevices().then(devices => {
  2816. devices[0].forget();
  2817. return {
  2818. vendorId: devices[0].vendorId,
  2819. productId: devices[0].productId,
  2820. name: devices[0].productName
  2821. }
  2822. })
  2823. `);
  2824. const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  2825. expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
  2826. if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) {
  2827. expect(deletedDeviceFromEvent).to.include(deletedDevice);
  2828. }
  2829. }
  2830. }
  2831. });
  2832. });
  2833. describe('navigator.usb', () => {
  2834. let w: BrowserWindow;
  2835. let server: http.Server;
  2836. let serverUrl: string;
  2837. before(async () => {
  2838. w = new BrowserWindow({
  2839. show: false
  2840. });
  2841. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2842. server = http.createServer((req, res) => {
  2843. res.setHeader('Content-Type', 'text/html');
  2844. res.end('<body>');
  2845. });
  2846. serverUrl = (await listen(server)).url;
  2847. });
  2848. const requestDevices: any = () => {
  2849. return w.webContents.executeJavaScript(`
  2850. navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
  2851. `, true);
  2852. };
  2853. const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.';
  2854. after(() => {
  2855. server.close();
  2856. closeAllWindows();
  2857. });
  2858. afterEach(() => {
  2859. session.defaultSession.setPermissionCheckHandler(null);
  2860. session.defaultSession.setDevicePermissionHandler(null);
  2861. session.defaultSession.removeAllListeners('select-usb-device');
  2862. });
  2863. it('does not return a device if select-usb-device event is not defined', async () => {
  2864. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2865. const device = await requestDevices();
  2866. expect(device).to.equal(notFoundError);
  2867. });
  2868. it('does not return a device when permission denied', async () => {
  2869. let selectFired = false;
  2870. w.webContents.session.on('select-usb-device', (event, details, callback) => {
  2871. selectFired = true;
  2872. callback();
  2873. });
  2874. session.defaultSession.setPermissionCheckHandler(() => false);
  2875. const device = await requestDevices();
  2876. expect(selectFired).to.be.false();
  2877. expect(device).to.equal(notFoundError);
  2878. });
  2879. it('returns a device when select-usb-device event is defined', async () => {
  2880. let haveDevices = false;
  2881. let selectFired = false;
  2882. w.webContents.session.on('select-usb-device', (event, details, callback) => {
  2883. expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
  2884. selectFired = true;
  2885. if (details.deviceList.length > 0) {
  2886. haveDevices = true;
  2887. callback(details.deviceList[0].deviceId);
  2888. } else {
  2889. callback();
  2890. }
  2891. });
  2892. const device = await requestDevices();
  2893. expect(selectFired).to.be.true();
  2894. if (haveDevices) {
  2895. expect(device).to.contain('[object USBDevice]');
  2896. } else {
  2897. expect(device).to.equal(notFoundError);
  2898. }
  2899. if (haveDevices) {
  2900. // Verify that navigation will clear device permissions
  2901. const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
  2902. expect(grantedDevices).to.not.be.empty();
  2903. w.loadURL(serverUrl);
  2904. const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
  2905. const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
  2906. expect(!!frame).to.be.true();
  2907. if (frame) {
  2908. const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()');
  2909. expect(grantedDevicesOnNewPage).to.be.empty();
  2910. }
  2911. }
  2912. });
  2913. it('returns a device when DevicePermissionHandler is defined', async () => {
  2914. let haveDevices = false;
  2915. let selectFired = false;
  2916. let gotDevicePerms = false;
  2917. w.webContents.session.on('select-usb-device', (event, details, callback) => {
  2918. selectFired = true;
  2919. if (details.deviceList.length > 0) {
  2920. const foundDevice = details.deviceList.find((device) => {
  2921. if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') {
  2922. haveDevices = true;
  2923. return true;
  2924. }
  2925. });
  2926. if (foundDevice) {
  2927. callback(foundDevice.deviceId);
  2928. return;
  2929. }
  2930. }
  2931. callback();
  2932. });
  2933. session.defaultSession.setDevicePermissionHandler(() => {
  2934. gotDevicePerms = true;
  2935. return true;
  2936. });
  2937. await w.webContents.executeJavaScript('navigator.usb.getDevices();', true);
  2938. const device = await requestDevices();
  2939. expect(selectFired).to.be.true();
  2940. if (haveDevices) {
  2941. expect(device).to.contain('[object USBDevice]');
  2942. expect(gotDevicePerms).to.be.true();
  2943. } else {
  2944. expect(device).to.equal(notFoundError);
  2945. }
  2946. });
  2947. it('supports device.forget()', async () => {
  2948. let deletedDeviceFromEvent;
  2949. let haveDevices = false;
  2950. w.webContents.session.on('select-usb-device', (event, details, callback) => {
  2951. if (details.deviceList.length > 0) {
  2952. haveDevices = true;
  2953. callback(details.deviceList[0].deviceId);
  2954. } else {
  2955. callback();
  2956. }
  2957. });
  2958. w.webContents.session.on('usb-device-revoked', (event, details) => {
  2959. deletedDeviceFromEvent = details.device;
  2960. });
  2961. await requestDevices();
  2962. if (haveDevices) {
  2963. const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
  2964. if (grantedDevices.length > 0) {
  2965. const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(`
  2966. navigator.usb.getDevices().then(devices => {
  2967. devices[0].forget();
  2968. return {
  2969. vendorId: devices[0].vendorId,
  2970. productId: devices[0].productId,
  2971. productName: devices[0].productName
  2972. }
  2973. })
  2974. `);
  2975. const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
  2976. expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
  2977. if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) {
  2978. expect(deletedDeviceFromEvent).to.include(deletedDevice);
  2979. }
  2980. }
  2981. }
  2982. });
  2983. });