chromium-spec.ts 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327
  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. for (const isSandboxEnabled of [true, false]) {
  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":"object","exports":"object","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. for (const storageName of ['localStorage', 'sessionStorage']) {
  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:// pages', () => {
  1833. const urls = [
  1834. 'chrome://accessibility',
  1835. 'chrome://gpu',
  1836. 'chrome://media-internals',
  1837. 'chrome://tracing',
  1838. 'chrome://webrtc-internals'
  1839. ];
  1840. for (const url of urls) {
  1841. describe(url, () => {
  1842. it('loads the page successfully', async () => {
  1843. const w = new BrowserWindow({ show: false });
  1844. await w.loadURL(url);
  1845. const pageExists = await w.webContents.executeJavaScript(
  1846. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1847. );
  1848. expect(pageExists).to.be.true();
  1849. });
  1850. });
  1851. }
  1852. });
  1853. describe('document.hasFocus', () => {
  1854. it('has correct value when multiple windows are opened', async () => {
  1855. const w1 = new BrowserWindow({ show: true });
  1856. const w2 = new BrowserWindow({ show: true });
  1857. const w3 = new BrowserWindow({ show: false });
  1858. await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1859. await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1860. await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1861. expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id);
  1862. let focus = false;
  1863. focus = await w1.webContents.executeJavaScript(
  1864. 'document.hasFocus()'
  1865. );
  1866. expect(focus).to.be.false();
  1867. focus = await w2.webContents.executeJavaScript(
  1868. 'document.hasFocus()'
  1869. );
  1870. expect(focus).to.be.true();
  1871. focus = await w3.webContents.executeJavaScript(
  1872. 'document.hasFocus()'
  1873. );
  1874. expect(focus).to.be.false();
  1875. });
  1876. });
  1877. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation
  1878. describe('navigator.connection', () => {
  1879. it('returns the correct value', async () => {
  1880. const w = new BrowserWindow({ show: false });
  1881. w.webContents.session.enableNetworkEmulation({
  1882. latency: 500,
  1883. downloadThroughput: 6400,
  1884. uploadThroughput: 6400
  1885. });
  1886. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1887. const rtt = await w.webContents.executeJavaScript('navigator.connection.rtt');
  1888. expect(rtt).to.be.a('number');
  1889. const downlink = await w.webContents.executeJavaScript('navigator.connection.downlink');
  1890. expect(downlink).to.be.a('number');
  1891. const effectiveTypes = ['slow-2g', '2g', '3g', '4g'];
  1892. const effectiveType = await w.webContents.executeJavaScript('navigator.connection.effectiveType');
  1893. expect(effectiveTypes).to.include(effectiveType);
  1894. });
  1895. });
  1896. describe('navigator.userAgentData', () => {
  1897. // These tests are done on an http server because navigator.userAgentData
  1898. // requires a secure context.
  1899. let server: http.Server;
  1900. let serverUrl: string;
  1901. before(async () => {
  1902. server = http.createServer((req, res) => {
  1903. res.setHeader('Content-Type', 'text/html');
  1904. res.end('');
  1905. });
  1906. serverUrl = (await listen(server)).url;
  1907. });
  1908. after(() => {
  1909. server.close();
  1910. });
  1911. describe('is not empty', () => {
  1912. it('by default', async () => {
  1913. const w = new BrowserWindow({ show: false });
  1914. await w.loadURL(serverUrl);
  1915. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1916. expect(platform).not.to.be.empty();
  1917. });
  1918. it('when there is a session-wide UA override', async () => {
  1919. const ses = session.fromPartition(`${Math.random()}`);
  1920. ses.setUserAgent('foobar');
  1921. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  1922. await w.loadURL(serverUrl);
  1923. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1924. expect(platform).not.to.be.empty();
  1925. });
  1926. it('when there is a WebContents-specific UA override', async () => {
  1927. const w = new BrowserWindow({ show: false });
  1928. w.webContents.setUserAgent('foo');
  1929. await w.loadURL(serverUrl);
  1930. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1931. expect(platform).not.to.be.empty();
  1932. });
  1933. it('when there is a WebContents-specific UA override at load time', async () => {
  1934. const w = new BrowserWindow({ show: false });
  1935. await w.loadURL(serverUrl, {
  1936. userAgent: 'foo'
  1937. });
  1938. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1939. expect(platform).not.to.be.empty();
  1940. });
  1941. });
  1942. describe('brand list', () => {
  1943. it('contains chromium', async () => {
  1944. const w = new BrowserWindow({ show: false });
  1945. await w.loadURL(serverUrl);
  1946. const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands');
  1947. expect(brands.map((b: any) => b.brand)).to.include('Chromium');
  1948. });
  1949. });
  1950. });
  1951. describe('Badging API', () => {
  1952. it('does not crash', async () => {
  1953. const w = new BrowserWindow({ show: false });
  1954. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1955. await w.webContents.executeJavaScript('navigator.setAppBadge(42)');
  1956. await w.webContents.executeJavaScript('navigator.setAppBadge()');
  1957. await w.webContents.executeJavaScript('navigator.clearAppBadge()');
  1958. });
  1959. });
  1960. describe('navigator.webkitGetUserMedia', () => {
  1961. it('calls its callbacks', async () => {
  1962. const w = new BrowserWindow({ show: false });
  1963. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1964. await w.webContents.executeJavaScript(`new Promise((resolve) => {
  1965. navigator.webkitGetUserMedia({
  1966. audio: true,
  1967. video: false
  1968. }, () => resolve(),
  1969. () => resolve());
  1970. })`);
  1971. });
  1972. });
  1973. describe('navigator.language', () => {
  1974. it('should not be empty', async () => {
  1975. const w = new BrowserWindow({ show: false });
  1976. await w.loadURL('about:blank');
  1977. expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal('');
  1978. });
  1979. });
  1980. describe('heap snapshot', () => {
  1981. it('does not crash', async () => {
  1982. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  1983. w.loadURL('about:blank');
  1984. await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()');
  1985. });
  1986. });
  1987. // This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761
  1988. ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => {
  1989. it('can be gotten as context in canvas', async () => {
  1990. const w = new BrowserWindow({ show: false });
  1991. w.loadURL('about:blank');
  1992. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  1993. const canWebglContextBeCreated = await w.webContents.executeJavaScript(`
  1994. document.createElement('canvas').getContext('webgl') != null;
  1995. `);
  1996. expect(canWebglContextBeCreated).to.be.true();
  1997. });
  1998. });
  1999. describe('iframe', () => {
  2000. it('does not have node integration', async () => {
  2001. const w = new BrowserWindow({ show: false });
  2002. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  2003. const result = await w.webContents.executeJavaScript(`
  2004. const iframe = document.createElement('iframe')
  2005. iframe.src = './set-global.html';
  2006. document.body.appendChild(iframe);
  2007. new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test))
  2008. `);
  2009. expect(result).to.equal('undefined undefined undefined');
  2010. });
  2011. });
  2012. describe('websockets', () => {
  2013. it('has user agent', async () => {
  2014. const server = http.createServer();
  2015. const { port } = await listen(server);
  2016. const wss = new ws.Server({ server: server });
  2017. const finished = new Promise<string | undefined>((resolve, reject) => {
  2018. wss.on('error', reject);
  2019. wss.on('connection', (ws, upgradeReq) => {
  2020. resolve(upgradeReq.headers['user-agent']);
  2021. });
  2022. });
  2023. const w = new BrowserWindow({ show: false });
  2024. w.loadURL('about:blank');
  2025. w.webContents.executeJavaScript(`
  2026. new WebSocket('ws://127.0.0.1:${port}');
  2027. `);
  2028. expect(await finished).to.include('Electron');
  2029. });
  2030. });
  2031. describe('fetch', () => {
  2032. it('does not crash', async () => {
  2033. const server = http.createServer((req, res) => {
  2034. res.end('test');
  2035. });
  2036. defer(() => server.close());
  2037. const { port } = await listen(server);
  2038. const w = new BrowserWindow({ show: false });
  2039. w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  2040. const x = await w.webContents.executeJavaScript(`
  2041. fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader())
  2042. .then((reader) => {
  2043. return reader.read().then((r) => {
  2044. reader.cancel();
  2045. return r.value;
  2046. });
  2047. })
  2048. `);
  2049. expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116]));
  2050. });
  2051. });
  2052. describe('Promise', () => {
  2053. before(() => {
  2054. ipcMain.handle('ping', (e, arg) => arg);
  2055. });
  2056. after(() => {
  2057. ipcMain.removeHandler('ping');
  2058. });
  2059. itremote('resolves correctly in Node.js calls', async () => {
  2060. await new Promise<void>((resolve, reject) => {
  2061. class XElement extends HTMLElement {}
  2062. customElements.define('x-element', XElement);
  2063. setImmediate(() => {
  2064. let called = false;
  2065. Promise.resolve().then(() => {
  2066. if (called) resolve();
  2067. else reject(new Error('wrong sequence'));
  2068. });
  2069. document.createElement('x-element');
  2070. called = true;
  2071. });
  2072. });
  2073. });
  2074. itremote('resolves correctly in Electron calls', async () => {
  2075. await new Promise<void>((resolve, reject) => {
  2076. class YElement extends HTMLElement {}
  2077. customElements.define('y-element', YElement);
  2078. require('electron').ipcRenderer.invoke('ping').then(() => {
  2079. let called = false;
  2080. Promise.resolve().then(() => {
  2081. if (called) resolve();
  2082. else reject(new Error('wrong sequence'));
  2083. });
  2084. document.createElement('y-element');
  2085. called = true;
  2086. });
  2087. });
  2088. });
  2089. });
  2090. describe('synchronous prompts', () => {
  2091. describe('window.alert(message, title)', () => {
  2092. itremote('throws an exception when the arguments cannot be converted to strings', () => {
  2093. expect(() => {
  2094. window.alert({ toString: null });
  2095. }).to.throw('Cannot convert object to primitive value');
  2096. });
  2097. });
  2098. describe('window.confirm(message, title)', () => {
  2099. itremote('throws an exception when the arguments cannot be converted to strings', () => {
  2100. expect(() => {
  2101. (window.confirm as any)({ toString: null }, 'title');
  2102. }).to.throw('Cannot convert object to primitive value');
  2103. });
  2104. });
  2105. });
  2106. describe('window.history', () => {
  2107. describe('window.history.go(offset)', () => {
  2108. itremote('throws an exception when the argument cannot be converted to a string', () => {
  2109. expect(() => {
  2110. (window.history.go as any)({ toString: null });
  2111. }).to.throw('Cannot convert object to primitive value');
  2112. });
  2113. });
  2114. });
  2115. describe('console functions', () => {
  2116. itremote('should exist', () => {
  2117. expect(console.log, 'log').to.be.a('function');
  2118. expect(console.error, 'error').to.be.a('function');
  2119. expect(console.warn, 'warn').to.be.a('function');
  2120. expect(console.info, 'info').to.be.a('function');
  2121. expect(console.debug, 'debug').to.be.a('function');
  2122. expect(console.trace, 'trace').to.be.a('function');
  2123. expect(console.time, 'time').to.be.a('function');
  2124. expect(console.timeEnd, 'timeEnd').to.be.a('function');
  2125. });
  2126. });
  2127. // FIXME(nornagon): this is broken on CI, it triggers:
  2128. // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will
  2129. // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side
  2130. // (null text in SpeechSynthesisUtterance struct).
  2131. describe('SpeechSynthesis', () => {
  2132. itremote('should emit lifecycle events', async () => {
  2133. const sentence = `long sentence which will take at least a few seconds to
  2134. utter so that it's possible to pause and resume before the end`;
  2135. const utter = new SpeechSynthesisUtterance(sentence);
  2136. // Create a dummy utterance so that speech synthesis state
  2137. // is initialized for later calls.
  2138. speechSynthesis.speak(new SpeechSynthesisUtterance());
  2139. speechSynthesis.cancel();
  2140. speechSynthesis.speak(utter);
  2141. // paused state after speak()
  2142. expect(speechSynthesis.paused).to.be.false();
  2143. await new Promise((resolve) => { utter.onstart = resolve; });
  2144. // paused state after start event
  2145. expect(speechSynthesis.paused).to.be.false();
  2146. speechSynthesis.pause();
  2147. // paused state changes async, right before the pause event
  2148. expect(speechSynthesis.paused).to.be.false();
  2149. await new Promise((resolve) => { utter.onpause = resolve; });
  2150. expect(speechSynthesis.paused).to.be.true();
  2151. speechSynthesis.resume();
  2152. await new Promise((resolve) => { utter.onresume = resolve; });
  2153. // paused state after resume event
  2154. expect(speechSynthesis.paused).to.be.false();
  2155. await new Promise((resolve) => { utter.onend = resolve; });
  2156. });
  2157. });
  2158. });
  2159. describe('font fallback', () => {
  2160. async function getRenderedFonts (html: string) {
  2161. const w = new BrowserWindow({ show: false });
  2162. try {
  2163. await w.loadURL(`data:text/html,${html}`);
  2164. w.webContents.debugger.attach();
  2165. const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
  2166. const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
  2167. await sendCommand('CSS.enable');
  2168. const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
  2169. return fonts;
  2170. } finally {
  2171. w.close();
  2172. }
  2173. }
  2174. it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
  2175. const html = '<body style="font-family: sans-serif">test</body>';
  2176. const fonts = await getRenderedFonts(html);
  2177. expect(fonts).to.be.an('array');
  2178. expect(fonts).to.have.length(1);
  2179. if (process.platform === 'win32') {
  2180. expect(fonts[0].familyName).to.equal('Arial');
  2181. } else if (process.platform === 'darwin') {
  2182. expect(fonts[0].familyName).to.equal('Helvetica');
  2183. } else if (process.platform === 'linux') {
  2184. expect(fonts[0].familyName).to.equal('DejaVu Sans');
  2185. } // I think this depends on the distro? We don't specify a default.
  2186. });
  2187. ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
  2188. const html = `
  2189. <html lang="ja-JP">
  2190. <head>
  2191. <meta charset="utf-8" />
  2192. </head>
  2193. <body style="font-family: sans-serif">test 智史</body>
  2194. </html>
  2195. `;
  2196. const fonts = await getRenderedFonts(html);
  2197. expect(fonts).to.be.an('array');
  2198. expect(fonts).to.have.length(1);
  2199. 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'); }
  2200. });
  2201. });
  2202. describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
  2203. const fullscreenChildHtml = promisify(fs.readFile)(
  2204. path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
  2205. );
  2206. let w: BrowserWindow;
  2207. let server: http.Server;
  2208. let crossSiteUrl: string;
  2209. beforeEach(async () => {
  2210. server = http.createServer(async (_req, res) => {
  2211. res.writeHead(200, { 'Content-Type': 'text/html' });
  2212. res.write(await fullscreenChildHtml);
  2213. res.end();
  2214. });
  2215. const serverUrl = (await listen(server)).url;
  2216. crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
  2217. w = new BrowserWindow({
  2218. show: true,
  2219. fullscreen: true,
  2220. webPreferences: {
  2221. nodeIntegration: true,
  2222. nodeIntegrationInSubFrames: true,
  2223. contextIsolation: false
  2224. }
  2225. });
  2226. });
  2227. afterEach(async () => {
  2228. await closeAllWindows();
  2229. (w as any) = null;
  2230. server.close();
  2231. });
  2232. ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => {
  2233. const fullscreenChange = once(ipcMain, 'fullscreenChange');
  2234. const html =
  2235. `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
  2236. w.loadURL(`data:text/html,${html}`);
  2237. await fullscreenChange;
  2238. const fullscreenWidth = await w.webContents.executeJavaScript(
  2239. "document.querySelector('iframe').offsetWidth"
  2240. );
  2241. expect(fullscreenWidth > 0).to.be.true();
  2242. await w.webContents.executeJavaScript(
  2243. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  2244. );
  2245. await setTimeout(500);
  2246. const width = await w.webContents.executeJavaScript(
  2247. "document.querySelector('iframe').offsetWidth"
  2248. );
  2249. expect(width).to.equal(0);
  2250. });
  2251. ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => {
  2252. await once(w, 'enter-full-screen');
  2253. const fullscreenChange = once(ipcMain, 'fullscreenChange');
  2254. const html =
  2255. `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
  2256. w.loadURL(`data:text/html,${html}`);
  2257. await fullscreenChange;
  2258. const fullscreenWidth = await w.webContents.executeJavaScript(
  2259. "document.querySelector('iframe').offsetWidth"
  2260. );
  2261. expect(fullscreenWidth > 0).to.be.true();
  2262. await w.webContents.executeJavaScript(
  2263. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  2264. );
  2265. await once(w.webContents, 'leave-html-full-screen');
  2266. const width = await w.webContents.executeJavaScript(
  2267. "document.querySelector('iframe').offsetWidth"
  2268. );
  2269. expect(width).to.equal(0);
  2270. w.setFullScreen(false);
  2271. await once(w, 'leave-full-screen');
  2272. });
  2273. // TODO(jkleinsc) fix this flaky test on WOA
  2274. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => {
  2275. if (process.platform === 'darwin') await once(w, 'enter-full-screen');
  2276. const fullscreenChange = once(ipcMain, 'fullscreenChange');
  2277. w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
  2278. await fullscreenChange;
  2279. const fullscreenWidth = await w.webContents.executeJavaScript(
  2280. "document.querySelector('iframe').offsetWidth"
  2281. );
  2282. expect(fullscreenWidth > 0).to.true();
  2283. await w.webContents.executeJavaScript('document.exitFullscreen()');
  2284. const width = await w.webContents.executeJavaScript(
  2285. "document.querySelector('iframe').offsetWidth"
  2286. );
  2287. expect(width).to.equal(0);
  2288. });
  2289. });
  2290. describe('navigator.serial', () => {
  2291. let w: BrowserWindow;
  2292. before(async () => {
  2293. w = new BrowserWindow({
  2294. show: false
  2295. });
  2296. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2297. });
  2298. const getPorts: any = () => {
  2299. return w.webContents.executeJavaScript(`
  2300. navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
  2301. `, true);
  2302. };
  2303. const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.';
  2304. after(closeAllWindows);
  2305. afterEach(() => {
  2306. session.defaultSession.setPermissionCheckHandler(null);
  2307. session.defaultSession.removeAllListeners('select-serial-port');
  2308. });
  2309. it('does not return a port if select-serial-port event is not defined', async () => {
  2310. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2311. const port = await getPorts();
  2312. expect(port).to.equal(notFoundError);
  2313. });
  2314. it('does not return a port when permission denied', async () => {
  2315. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2316. callback(portList[0].portId);
  2317. });
  2318. session.defaultSession.setPermissionCheckHandler(() => false);
  2319. const port = await getPorts();
  2320. expect(port).to.equal(notFoundError);
  2321. });
  2322. it('does not crash when select-serial-port is called with an invalid port', async () => {
  2323. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2324. callback('i-do-not-exist');
  2325. });
  2326. const port = await getPorts();
  2327. expect(port).to.equal(notFoundError);
  2328. });
  2329. it('returns a port when select-serial-port event is defined', async () => {
  2330. let havePorts = false;
  2331. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2332. if (portList.length > 0) {
  2333. havePorts = true;
  2334. callback(portList[0].portId);
  2335. } else {
  2336. callback('');
  2337. }
  2338. });
  2339. const port = await getPorts();
  2340. if (havePorts) {
  2341. expect(port).to.equal('[object SerialPort]');
  2342. } else {
  2343. expect(port).to.equal(notFoundError);
  2344. }
  2345. });
  2346. it('navigator.serial.getPorts() returns values', async () => {
  2347. let havePorts = false;
  2348. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2349. if (portList.length > 0) {
  2350. havePorts = true;
  2351. callback(portList[0].portId);
  2352. } else {
  2353. callback('');
  2354. }
  2355. });
  2356. await getPorts();
  2357. if (havePorts) {
  2358. const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
  2359. expect(grantedPorts).to.not.be.empty();
  2360. }
  2361. });
  2362. it('supports port.forget()', async () => {
  2363. let forgottenPortFromEvent = {};
  2364. let havePorts = false;
  2365. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  2366. if (portList.length > 0) {
  2367. havePorts = true;
  2368. callback(portList[0].portId);
  2369. } else {
  2370. callback('');
  2371. }
  2372. });
  2373. w.webContents.session.on('serial-port-revoked', (event, details) => {
  2374. forgottenPortFromEvent = details.port;
  2375. });
  2376. await getPorts();
  2377. if (havePorts) {
  2378. const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
  2379. if (grantedPorts.length > 0) {
  2380. const forgottenPort = await w.webContents.executeJavaScript(`
  2381. navigator.serial.getPorts().then(async(ports) => {
  2382. const portInfo = await ports[0].getInfo();
  2383. await ports[0].forget();
  2384. if (portInfo.usbVendorId && portInfo.usbProductId) {
  2385. return {
  2386. vendorId: '' + portInfo.usbVendorId,
  2387. productId: '' + portInfo.usbProductId
  2388. }
  2389. } else {
  2390. return {};
  2391. }
  2392. })
  2393. `);
  2394. const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
  2395. expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length);
  2396. if (forgottenPort.vendorId && forgottenPort.productId) {
  2397. expect(forgottenPortFromEvent).to.include(forgottenPort);
  2398. }
  2399. }
  2400. }
  2401. });
  2402. });
  2403. describe('window.getScreenDetails', () => {
  2404. let w: BrowserWindow;
  2405. before(async () => {
  2406. w = new BrowserWindow({
  2407. show: false
  2408. });
  2409. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2410. });
  2411. after(closeAllWindows);
  2412. afterEach(() => {
  2413. session.defaultSession.setPermissionRequestHandler(null);
  2414. });
  2415. const getScreenDetails: any = () => {
  2416. return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true);
  2417. };
  2418. it('returns screens when a PermissionRequestHandler is not defined', async () => {
  2419. const screens = await getScreenDetails();
  2420. expect(screens).to.not.equal('Read permission denied.');
  2421. });
  2422. it('returns an error when permission denied', async () => {
  2423. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2424. if (permission === 'window-management') {
  2425. callback(false);
  2426. } else {
  2427. callback(true);
  2428. }
  2429. });
  2430. const screens = await getScreenDetails();
  2431. expect(screens).to.equal('Permission denied.');
  2432. });
  2433. it('returns screens when permission is granted', async () => {
  2434. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2435. if (permission === 'window-management') {
  2436. callback(true);
  2437. } else {
  2438. callback(false);
  2439. }
  2440. });
  2441. const screens = await getScreenDetails();
  2442. expect(screens).to.not.equal('Permission denied.');
  2443. });
  2444. });
  2445. describe('navigator.clipboard.read', () => {
  2446. let w: BrowserWindow;
  2447. before(async () => {
  2448. w = new BrowserWindow();
  2449. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2450. });
  2451. const readClipboard: any = () => {
  2452. return w.webContents.executeJavaScript(`
  2453. navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
  2454. `, true);
  2455. };
  2456. after(closeAllWindows);
  2457. afterEach(() => {
  2458. session.defaultSession.setPermissionRequestHandler(null);
  2459. });
  2460. it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
  2461. const clipboard = await readClipboard();
  2462. expect(clipboard).to.not.equal('Read permission denied.');
  2463. });
  2464. it('returns an error when permission denied', async () => {
  2465. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2466. if (permission === 'clipboard-read') {
  2467. callback(false);
  2468. } else {
  2469. callback(true);
  2470. }
  2471. });
  2472. const clipboard = await readClipboard();
  2473. expect(clipboard).to.equal('Read permission denied.');
  2474. });
  2475. it('returns clipboard contents when permission is granted', async () => {
  2476. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2477. if (permission === 'clipboard-read') {
  2478. callback(true);
  2479. } else {
  2480. callback(false);
  2481. }
  2482. });
  2483. const clipboard = await readClipboard();
  2484. expect(clipboard).to.not.equal('Read permission denied.');
  2485. });
  2486. });
  2487. describe('navigator.clipboard.write', () => {
  2488. let w: BrowserWindow;
  2489. before(async () => {
  2490. w = new BrowserWindow();
  2491. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2492. });
  2493. const writeClipboard: any = () => {
  2494. return w.webContents.executeJavaScript(`
  2495. navigator.clipboard.writeText('Hello World!').catch(err => err.message);
  2496. `, true);
  2497. };
  2498. after(closeAllWindows);
  2499. afterEach(() => {
  2500. session.defaultSession.setPermissionRequestHandler(null);
  2501. });
  2502. it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
  2503. const clipboard = await writeClipboard();
  2504. expect(clipboard).to.not.equal('Write permission denied.');
  2505. });
  2506. it('returns an error when permission denied', async () => {
  2507. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2508. if (permission === 'clipboard-sanitized-write') {
  2509. callback(false);
  2510. } else {
  2511. callback(true);
  2512. }
  2513. });
  2514. const clipboard = await writeClipboard();
  2515. expect(clipboard).to.equal('Write permission denied.');
  2516. });
  2517. it('returns clipboard contents when permission is granted', async () => {
  2518. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  2519. if (permission === 'clipboard-sanitized-write') {
  2520. callback(true);
  2521. } else {
  2522. callback(false);
  2523. }
  2524. });
  2525. const clipboard = await writeClipboard();
  2526. expect(clipboard).to.not.equal('Write permission denied.');
  2527. });
  2528. });
  2529. ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
  2530. let w: BrowserWindow;
  2531. const expectedBadgeCount = 42;
  2532. const fireAppBadgeAction: any = (action: string, value: any) => {
  2533. return w.webContents.executeJavaScript(`
  2534. navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
  2535. };
  2536. // For some reason on macOS changing the badge count doesn't happen right away, so wait
  2537. // until it changes.
  2538. async function waitForBadgeCount (value: number) {
  2539. let badgeCount = app.getBadgeCount();
  2540. while (badgeCount !== value) {
  2541. await setTimeout(10);
  2542. badgeCount = app.getBadgeCount();
  2543. }
  2544. return badgeCount;
  2545. }
  2546. describe('in the renderer', () => {
  2547. before(async () => {
  2548. w = new BrowserWindow({
  2549. show: false
  2550. });
  2551. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2552. });
  2553. after(() => {
  2554. app.badgeCount = 0;
  2555. closeAllWindows();
  2556. });
  2557. it('setAppBadge can set a numerical value', async () => {
  2558. const result = await fireAppBadgeAction('set', expectedBadgeCount);
  2559. expect(result).to.equal('success');
  2560. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2561. });
  2562. it('setAppBadge can set an empty(dot) value', async () => {
  2563. const result = await fireAppBadgeAction('set');
  2564. expect(result).to.equal('success');
  2565. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  2566. });
  2567. it('clearAppBadge can clear a value', async () => {
  2568. let result = await fireAppBadgeAction('set', expectedBadgeCount);
  2569. expect(result).to.equal('success');
  2570. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2571. result = await fireAppBadgeAction('clear');
  2572. expect(result).to.equal('success');
  2573. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  2574. });
  2575. });
  2576. describe('in a service worker', () => {
  2577. beforeEach(async () => {
  2578. w = new BrowserWindow({
  2579. show: false,
  2580. webPreferences: {
  2581. nodeIntegration: true,
  2582. partition: 'sw-file-scheme-spec',
  2583. contextIsolation: false
  2584. }
  2585. });
  2586. });
  2587. afterEach(() => {
  2588. app.badgeCount = 0;
  2589. closeAllWindows();
  2590. });
  2591. it('setAppBadge can be called in a ServiceWorker', (done) => {
  2592. w.webContents.on('ipc-message', (event, channel, message) => {
  2593. if (channel === 'reload') {
  2594. w.webContents.reload();
  2595. } else if (channel === 'error') {
  2596. done(message);
  2597. } else if (channel === 'response') {
  2598. expect(message).to.equal('SUCCESS setting app badge');
  2599. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2600. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  2601. storages: ['serviceworkers']
  2602. }).then(() => done());
  2603. }
  2604. });
  2605. w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
  2606. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
  2607. });
  2608. it('clearAppBadge can be called in a ServiceWorker', (done) => {
  2609. w.webContents.on('ipc-message', (event, channel, message) => {
  2610. if (channel === 'reload') {
  2611. w.webContents.reload();
  2612. } else if (channel === 'setAppBadge') {
  2613. expect(message).to.equal('SUCCESS setting app badge');
  2614. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2615. } else if (channel === 'error') {
  2616. done(message);
  2617. } else if (channel === 'response') {
  2618. expect(message).to.equal('SUCCESS clearing app badge');
  2619. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  2620. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  2621. storages: ['serviceworkers']
  2622. }).then(() => done());
  2623. }
  2624. });
  2625. w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
  2626. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
  2627. });
  2628. });
  2629. });
  2630. describe('navigator.bluetooth', () => {
  2631. let w: BrowserWindow;
  2632. before(async () => {
  2633. w = new BrowserWindow({
  2634. show: false,
  2635. webPreferences: {
  2636. enableBlinkFeatures: 'WebBluetooth'
  2637. }
  2638. });
  2639. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2640. });
  2641. after(closeAllWindows);
  2642. it('can request bluetooth devices', async () => {
  2643. const bluetooth = await w.webContents.executeJavaScript(`
  2644. navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
  2645. expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
  2646. });
  2647. });
  2648. describe('navigator.hid', () => {
  2649. let w: BrowserWindow;
  2650. let server: http.Server;
  2651. let serverUrl: string;
  2652. before(async () => {
  2653. w = new BrowserWindow({
  2654. show: false
  2655. });
  2656. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2657. server = http.createServer((req, res) => {
  2658. res.setHeader('Content-Type', 'text/html');
  2659. res.end('<body>');
  2660. });
  2661. serverUrl = (await listen(server)).url;
  2662. });
  2663. const requestDevices: any = () => {
  2664. return w.webContents.executeJavaScript(`
  2665. navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
  2666. `, true);
  2667. };
  2668. after(() => {
  2669. server.close();
  2670. closeAllWindows();
  2671. });
  2672. afterEach(() => {
  2673. session.defaultSession.setPermissionCheckHandler(null);
  2674. session.defaultSession.setDevicePermissionHandler(null);
  2675. session.defaultSession.removeAllListeners('select-hid-device');
  2676. });
  2677. it('does not return a device if select-hid-device event is not defined', async () => {
  2678. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2679. const device = await requestDevices();
  2680. expect(device).to.equal('');
  2681. });
  2682. it('does not return a device when permission denied', async () => {
  2683. let selectFired = false;
  2684. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2685. selectFired = true;
  2686. callback();
  2687. });
  2688. session.defaultSession.setPermissionCheckHandler(() => false);
  2689. const device = await requestDevices();
  2690. expect(selectFired).to.be.false();
  2691. expect(device).to.equal('');
  2692. });
  2693. it('returns a device when select-hid-device event is defined', async () => {
  2694. let haveDevices = false;
  2695. let selectFired = false;
  2696. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2697. expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
  2698. selectFired = true;
  2699. if (details.deviceList.length > 0) {
  2700. haveDevices = true;
  2701. callback(details.deviceList[0].deviceId);
  2702. } else {
  2703. callback();
  2704. }
  2705. });
  2706. const device = await requestDevices();
  2707. expect(selectFired).to.be.true();
  2708. if (haveDevices) {
  2709. expect(device).to.contain('[object HIDDevice]');
  2710. } else {
  2711. expect(device).to.equal('');
  2712. }
  2713. if (haveDevices) {
  2714. // Verify that navigation will clear device permissions
  2715. const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  2716. expect(grantedDevices).to.not.be.empty();
  2717. w.loadURL(serverUrl);
  2718. const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
  2719. const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
  2720. expect(!!frame).to.be.true();
  2721. if (frame) {
  2722. const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
  2723. expect(grantedDevicesOnNewPage).to.be.empty();
  2724. }
  2725. }
  2726. });
  2727. it('returns a device when DevicePermissionHandler is defined', async () => {
  2728. let haveDevices = false;
  2729. let selectFired = false;
  2730. let gotDevicePerms = false;
  2731. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2732. selectFired = true;
  2733. if (details.deviceList.length > 0) {
  2734. const foundDevice = details.deviceList.find((device) => {
  2735. if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
  2736. haveDevices = true;
  2737. return true;
  2738. }
  2739. });
  2740. if (foundDevice) {
  2741. callback(foundDevice.deviceId);
  2742. return;
  2743. }
  2744. }
  2745. callback();
  2746. });
  2747. session.defaultSession.setDevicePermissionHandler(() => {
  2748. gotDevicePerms = true;
  2749. return true;
  2750. });
  2751. await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
  2752. const device = await requestDevices();
  2753. expect(selectFired).to.be.true();
  2754. if (haveDevices) {
  2755. expect(device).to.contain('[object HIDDevice]');
  2756. expect(gotDevicePerms).to.be.true();
  2757. } else {
  2758. expect(device).to.equal('');
  2759. }
  2760. });
  2761. it('excludes a device when a exclusionFilter is specified', async () => {
  2762. const exclusionFilters = <any>[];
  2763. let haveDevices = false;
  2764. let checkForExcludedDevice = false;
  2765. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2766. if (details.deviceList.length > 0) {
  2767. details.deviceList.find((device) => {
  2768. if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
  2769. if (checkForExcludedDevice) {
  2770. const compareDevice = {
  2771. vendorId: device.vendorId,
  2772. productId: device.productId
  2773. };
  2774. expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned');
  2775. } else {
  2776. haveDevices = true;
  2777. exclusionFilters.push({
  2778. vendorId: device.vendorId,
  2779. productId: device.productId
  2780. });
  2781. return true;
  2782. }
  2783. }
  2784. });
  2785. }
  2786. callback();
  2787. });
  2788. await requestDevices();
  2789. if (haveDevices) {
  2790. // We have devices to exclude, so check if exclusionFilters work
  2791. checkForExcludedDevice = true;
  2792. await w.webContents.executeJavaScript(`
  2793. navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString());
  2794. `, true);
  2795. }
  2796. });
  2797. it('supports device.forget()', async () => {
  2798. let deletedDeviceFromEvent;
  2799. let haveDevices = false;
  2800. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  2801. if (details.deviceList.length > 0) {
  2802. haveDevices = true;
  2803. callback(details.deviceList[0].deviceId);
  2804. } else {
  2805. callback();
  2806. }
  2807. });
  2808. w.webContents.session.on('hid-device-revoked', (event, details) => {
  2809. deletedDeviceFromEvent = details.device;
  2810. });
  2811. await requestDevices();
  2812. if (haveDevices) {
  2813. const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  2814. if (grantedDevices.length > 0) {
  2815. const deletedDevice = await w.webContents.executeJavaScript(`
  2816. navigator.hid.getDevices().then(devices => {
  2817. devices[0].forget();
  2818. return {
  2819. vendorId: devices[0].vendorId,
  2820. productId: devices[0].productId,
  2821. name: devices[0].productName
  2822. }
  2823. })
  2824. `);
  2825. const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  2826. expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
  2827. if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) {
  2828. expect(deletedDeviceFromEvent).to.include(deletedDevice);
  2829. }
  2830. }
  2831. }
  2832. });
  2833. });
  2834. describe('navigator.usb', () => {
  2835. let w: BrowserWindow;
  2836. let server: http.Server;
  2837. let serverUrl: string;
  2838. before(async () => {
  2839. w = new BrowserWindow({
  2840. show: false
  2841. });
  2842. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2843. server = http.createServer((req, res) => {
  2844. res.setHeader('Content-Type', 'text/html');
  2845. res.end('<body>');
  2846. });
  2847. serverUrl = (await listen(server)).url;
  2848. });
  2849. const requestDevices: any = () => {
  2850. return w.webContents.executeJavaScript(`
  2851. navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
  2852. `, true);
  2853. };
  2854. const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.';
  2855. after(() => {
  2856. server.close();
  2857. closeAllWindows();
  2858. });
  2859. afterEach(() => {
  2860. session.defaultSession.setPermissionCheckHandler(null);
  2861. session.defaultSession.setDevicePermissionHandler(null);
  2862. session.defaultSession.removeAllListeners('select-usb-device');
  2863. });
  2864. it('does not return a device if select-usb-device event is not defined', async () => {
  2865. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  2866. const device = await requestDevices();
  2867. expect(device).to.equal(notFoundError);
  2868. });
  2869. it('does not return a device when permission denied', async () => {
  2870. let selectFired = false;
  2871. w.webContents.session.on('select-usb-device', (event, details, callback) => {
  2872. selectFired = true;
  2873. callback();
  2874. });
  2875. session.defaultSession.setPermissionCheckHandler(() => false);
  2876. const device = await requestDevices();
  2877. expect(selectFired).to.be.false();
  2878. expect(device).to.equal(notFoundError);
  2879. });
  2880. it('returns a device when select-usb-device event is defined', async () => {
  2881. let haveDevices = false;
  2882. let selectFired = false;
  2883. w.webContents.session.on('select-usb-device', (event, details, callback) => {
  2884. expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
  2885. selectFired = true;
  2886. if (details.deviceList.length > 0) {
  2887. haveDevices = true;
  2888. callback(details.deviceList[0].deviceId);
  2889. } else {
  2890. callback();
  2891. }
  2892. });
  2893. const device = await requestDevices();
  2894. expect(selectFired).to.be.true();
  2895. if (haveDevices) {
  2896. expect(device).to.contain('[object USBDevice]');
  2897. } else {
  2898. expect(device).to.equal(notFoundError);
  2899. }
  2900. if (haveDevices) {
  2901. // Verify that navigation will clear device permissions
  2902. const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
  2903. expect(grantedDevices).to.not.be.empty();
  2904. w.loadURL(serverUrl);
  2905. const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
  2906. const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
  2907. expect(!!frame).to.be.true();
  2908. if (frame) {
  2909. const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()');
  2910. expect(grantedDevicesOnNewPage).to.be.empty();
  2911. }
  2912. }
  2913. });
  2914. it('returns a device when DevicePermissionHandler is defined', async () => {
  2915. let haveDevices = false;
  2916. let selectFired = false;
  2917. let gotDevicePerms = false;
  2918. w.webContents.session.on('select-usb-device', (event, details, callback) => {
  2919. selectFired = true;
  2920. if (details.deviceList.length > 0) {
  2921. const foundDevice = details.deviceList.find((device) => {
  2922. if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') {
  2923. haveDevices = true;
  2924. return true;
  2925. }
  2926. });
  2927. if (foundDevice) {
  2928. callback(foundDevice.deviceId);
  2929. return;
  2930. }
  2931. }
  2932. callback();
  2933. });
  2934. session.defaultSession.setDevicePermissionHandler(() => {
  2935. gotDevicePerms = true;
  2936. return true;
  2937. });
  2938. await w.webContents.executeJavaScript('navigator.usb.getDevices();', true);
  2939. const device = await requestDevices();
  2940. expect(selectFired).to.be.true();
  2941. if (haveDevices) {
  2942. expect(device).to.contain('[object USBDevice]');
  2943. expect(gotDevicePerms).to.be.true();
  2944. } else {
  2945. expect(device).to.equal(notFoundError);
  2946. }
  2947. });
  2948. it('supports device.forget()', async () => {
  2949. let deletedDeviceFromEvent;
  2950. let haveDevices = false;
  2951. w.webContents.session.on('select-usb-device', (event, details, callback) => {
  2952. if (details.deviceList.length > 0) {
  2953. haveDevices = true;
  2954. callback(details.deviceList[0].deviceId);
  2955. } else {
  2956. callback();
  2957. }
  2958. });
  2959. w.webContents.session.on('usb-device-revoked', (event, details) => {
  2960. deletedDeviceFromEvent = details.device;
  2961. });
  2962. await requestDevices();
  2963. if (haveDevices) {
  2964. const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
  2965. if (grantedDevices.length > 0) {
  2966. const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(`
  2967. navigator.usb.getDevices().then(devices => {
  2968. devices[0].forget();
  2969. return {
  2970. vendorId: devices[0].vendorId,
  2971. productId: devices[0].productId,
  2972. productName: devices[0].productName
  2973. }
  2974. })
  2975. `);
  2976. const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
  2977. expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
  2978. if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) {
  2979. expect(deletedDeviceFromEvent).to.include(deletedDevice);
  2980. }
  2981. }
  2982. }
  2983. });
  2984. });