chromium-spec.ts 124 KB

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