chromium-spec.ts 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133
  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, delay, defer } from './spec-helpers';
  14. import { AddressInfo } from 'net';
  15. import { PipeTransport } from './pipe-transport';
  16. const features = process._linkedBinding('electron_common_features');
  17. const fixturesPath = path.resolve(__dirname, '..', 'spec', 'fixtures');
  18. describe('reporting api', () => {
  19. // TODO(nornagon): this started failing a lot on CI. Figure out why and fix
  20. // it.
  21. it.skip('sends a report for a deprecation', async () => {
  22. const reports = new EventEmitter();
  23. // The Reporting API only works on https with valid certs. To dodge having
  24. // to set up a trusted certificate, hack the validator.
  25. session.defaultSession.setCertificateVerifyProc((req, cb) => {
  26. cb(0);
  27. });
  28. const certPath = path.join(fixturesPath, 'certificates');
  29. const options = {
  30. key: fs.readFileSync(path.join(certPath, 'server.key')),
  31. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  32. ca: [
  33. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  34. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  35. ],
  36. requestCert: true,
  37. rejectUnauthorized: false
  38. };
  39. const server = https.createServer(options, (req, res) => {
  40. if (req.url === '/report') {
  41. let data = '';
  42. req.on('data', (d) => { data += d.toString('utf-8'); });
  43. req.on('end', () => {
  44. reports.emit('report', JSON.parse(data));
  45. });
  46. }
  47. res.setHeader('Report-To', JSON.stringify({
  48. group: 'default',
  49. max_age: 120,
  50. endpoints: [{ url: `https://localhost:${(server.address() as any).port}/report` }]
  51. }));
  52. res.setHeader('Content-Type', 'text/html');
  53. // using the deprecated `webkitRequestAnimationFrame` will trigger a
  54. // "deprecation" report.
  55. res.end('<script>webkitRequestAnimationFrame(() => {})</script>');
  56. });
  57. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  58. const bw = new BrowserWindow({
  59. show: false
  60. });
  61. try {
  62. const reportGenerated = emittedOnce(reports, 'report');
  63. const url = `https://localhost:${(server.address() as any).port}/a`;
  64. await bw.loadURL(url);
  65. const [report] = await reportGenerated;
  66. expect(report).to.be.an('array');
  67. expect(report[0].type).to.equal('deprecation');
  68. expect(report[0].url).to.equal(url);
  69. expect(report[0].body.id).to.equal('PrefixedRequestAnimationFrame');
  70. } finally {
  71. bw.destroy();
  72. server.close();
  73. }
  74. });
  75. });
  76. describe('window.postMessage', () => {
  77. afterEach(async () => {
  78. await closeAllWindows();
  79. });
  80. for (const nativeWindowOpen of [true, false]) {
  81. describe(`when nativeWindowOpen: ${nativeWindowOpen}`, () => {
  82. it('sets the source and origin correctly', async () => {
  83. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nativeWindowOpen, contextIsolation: false } });
  84. w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`);
  85. const [, message] = await emittedOnce(ipcMain, 'complete');
  86. expect(message.data).to.equal('testing');
  87. expect(message.origin).to.equal('file://');
  88. expect(message.sourceEqualsOpener).to.equal(true);
  89. expect(message.eventOrigin).to.equal('file://');
  90. });
  91. });
  92. }
  93. });
  94. describe('focus handling', () => {
  95. let webviewContents: WebContents = null as unknown as WebContents;
  96. let w: BrowserWindow = null as unknown as BrowserWindow;
  97. beforeEach(async () => {
  98. w = new BrowserWindow({
  99. show: true,
  100. webPreferences: {
  101. nodeIntegration: true,
  102. webviewTag: true,
  103. contextIsolation: false
  104. }
  105. });
  106. const webviewReady = emittedOnce(w.webContents, 'did-attach-webview');
  107. await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html'));
  108. const [, wvContents] = await webviewReady;
  109. webviewContents = wvContents;
  110. await emittedOnce(webviewContents, 'did-finish-load');
  111. w.focus();
  112. });
  113. afterEach(() => {
  114. webviewContents = null as unknown as WebContents;
  115. w.destroy();
  116. w = null as unknown as BrowserWindow;
  117. });
  118. const expectFocusChange = async () => {
  119. const [, focusedElementId] = await emittedOnce(ipcMain, 'focus-changed');
  120. return focusedElementId;
  121. };
  122. describe('a TAB press', () => {
  123. const tabPressEvent: any = {
  124. type: 'keyDown',
  125. keyCode: 'Tab'
  126. };
  127. it('moves focus to the next focusable item', async () => {
  128. let focusChange = expectFocusChange();
  129. w.webContents.sendInputEvent(tabPressEvent);
  130. let focusedElementId = await focusChange;
  131. expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`);
  132. focusChange = expectFocusChange();
  133. w.webContents.sendInputEvent(tabPressEvent);
  134. focusedElementId = await focusChange;
  135. expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
  136. focusChange = expectFocusChange();
  137. w.webContents.sendInputEvent(tabPressEvent);
  138. focusedElementId = await focusChange;
  139. expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
  140. focusChange = expectFocusChange();
  141. webviewContents.sendInputEvent(tabPressEvent);
  142. focusedElementId = await focusChange;
  143. expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
  144. focusChange = expectFocusChange();
  145. webviewContents.sendInputEvent(tabPressEvent);
  146. focusedElementId = await focusChange;
  147. expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`);
  148. focusChange = expectFocusChange();
  149. w.webContents.sendInputEvent(tabPressEvent);
  150. focusedElementId = await focusChange;
  151. expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`);
  152. });
  153. });
  154. describe('a SHIFT + TAB press', () => {
  155. const shiftTabPressEvent: any = {
  156. type: 'keyDown',
  157. modifiers: ['Shift'],
  158. keyCode: 'Tab'
  159. };
  160. it('moves focus to the previous focusable item', async () => {
  161. let focusChange = expectFocusChange();
  162. w.webContents.sendInputEvent(shiftTabPressEvent);
  163. let focusedElementId = await focusChange;
  164. expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`);
  165. focusChange = expectFocusChange();
  166. w.webContents.sendInputEvent(shiftTabPressEvent);
  167. focusedElementId = await focusChange;
  168. expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
  169. focusChange = expectFocusChange();
  170. webviewContents.sendInputEvent(shiftTabPressEvent);
  171. focusedElementId = await focusChange;
  172. expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
  173. focusChange = expectFocusChange();
  174. webviewContents.sendInputEvent(shiftTabPressEvent);
  175. focusedElementId = await focusChange;
  176. expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
  177. focusChange = expectFocusChange();
  178. w.webContents.sendInputEvent(shiftTabPressEvent);
  179. focusedElementId = await focusChange;
  180. expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`);
  181. focusChange = expectFocusChange();
  182. w.webContents.sendInputEvent(shiftTabPressEvent);
  183. focusedElementId = await focusChange;
  184. expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`);
  185. });
  186. });
  187. });
  188. describe('web security', () => {
  189. afterEach(closeAllWindows);
  190. let server: http.Server;
  191. let serverUrl: string;
  192. before(async () => {
  193. server = http.createServer((req, res) => {
  194. res.setHeader('Content-Type', 'text/html');
  195. res.end('<body>');
  196. });
  197. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  198. serverUrl = `http://localhost:${(server.address() as any).port}`;
  199. });
  200. after(() => {
  201. server.close();
  202. });
  203. it('engages CORB when web security is not disabled', async () => {
  204. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
  205. const p = emittedOnce(ipcMain, 'success');
  206. await w.loadURL(`data:text/html,<script>
  207. const s = document.createElement('script')
  208. s.src = "${serverUrl}"
  209. // The script will load successfully but its body will be emptied out
  210. // by CORB, so we don't expect a syntax error.
  211. s.onload = () => { require('electron').ipcRenderer.send('success') }
  212. document.documentElement.appendChild(s)
  213. </script>`);
  214. await p;
  215. });
  216. // TODO(codebytere): Re-enable after Chromium fixes upstream v8_scriptormodule_legacy_lifetime crash.
  217. xit('bypasses CORB when web security is disabled', async () => {
  218. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
  219. const p = emittedOnce(ipcMain, 'success');
  220. await w.loadURL(`data:text/html,
  221. <script>
  222. window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) }
  223. </script>
  224. <script src="${serverUrl}"></script>`);
  225. await p;
  226. });
  227. it('engages CORS when web security is not disabled', async () => {
  228. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
  229. const p = emittedOnce(ipcMain, 'response');
  230. await w.loadURL(`data:text/html,<script>
  231. (async function() {
  232. try {
  233. await fetch('${serverUrl}');
  234. require('electron').ipcRenderer.send('response', 'passed');
  235. } catch {
  236. require('electron').ipcRenderer.send('response', 'failed');
  237. }
  238. })();
  239. </script>`);
  240. const [, response] = await p;
  241. expect(response).to.equal('failed');
  242. });
  243. it('bypasses CORS when web security is disabled', async () => {
  244. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
  245. const p = emittedOnce(ipcMain, 'response');
  246. await w.loadURL(`data:text/html,<script>
  247. (async function() {
  248. try {
  249. await fetch('${serverUrl}');
  250. require('electron').ipcRenderer.send('response', 'passed');
  251. } catch {
  252. require('electron').ipcRenderer.send('response', 'failed');
  253. }
  254. })();
  255. </script>`);
  256. const [, response] = await p;
  257. expect(response).to.equal('passed');
  258. });
  259. describe('accessing file://', () => {
  260. async function loadFile (w: BrowserWindow) {
  261. const thisFile = url.format({
  262. pathname: __filename.replace(/\\/g, '/'),
  263. protocol: 'file',
  264. slashes: true
  265. });
  266. await w.loadURL(`data:text/html,<script>
  267. function loadFile() {
  268. return new Promise((resolve) => {
  269. fetch('${thisFile}').then(
  270. () => resolve('loaded'),
  271. () => resolve('failed')
  272. )
  273. });
  274. }
  275. </script>`);
  276. return await w.webContents.executeJavaScript('loadFile()');
  277. }
  278. it('is forbidden when web security is enabled', async () => {
  279. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } });
  280. const result = await loadFile(w);
  281. expect(result).to.equal('failed');
  282. });
  283. it('is allowed when web security is disabled', async () => {
  284. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } });
  285. const result = await loadFile(w);
  286. expect(result).to.equal('loaded');
  287. });
  288. });
  289. describe('wasm-eval csp', () => {
  290. async function loadWasm (csp: string) {
  291. const w = new BrowserWindow({
  292. show: false,
  293. webPreferences: {
  294. sandbox: true,
  295. enableBlinkFeatures: 'WebAssemblyCSP'
  296. }
  297. });
  298. await w.loadURL(`data:text/html,<head>
  299. <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}">
  300. </head>
  301. <script>
  302. function loadWasm() {
  303. const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
  304. return new Promise((resolve) => {
  305. WebAssembly.instantiate(wasmBin).then(() => {
  306. resolve('loaded')
  307. }).catch((error) => {
  308. resolve(error.message)
  309. })
  310. });
  311. }
  312. </script>`);
  313. return await w.webContents.executeJavaScript('loadWasm()');
  314. }
  315. it('wasm codegen is disallowed by default', async () => {
  316. const r = await loadWasm('');
  317. expect(r).to.equal('WebAssembly.instantiate(): Wasm code generation disallowed by embedder');
  318. });
  319. it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => {
  320. const r = await loadWasm("'wasm-unsafe-eval'");
  321. expect(r).to.equal('loaded');
  322. });
  323. });
  324. it('does not crash when multiple WebContent are created with web security disabled', () => {
  325. const options = { show: false, webPreferences: { webSecurity: false } };
  326. const w1 = new BrowserWindow(options);
  327. w1.loadURL(serverUrl);
  328. const w2 = new BrowserWindow(options);
  329. w2.loadURL(serverUrl);
  330. });
  331. });
  332. describe('command line switches', () => {
  333. let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
  334. afterEach(() => {
  335. if (appProcess && !appProcess.killed) {
  336. appProcess.kill();
  337. appProcess = undefined;
  338. }
  339. });
  340. describe('--lang switch', () => {
  341. const currentLocale = app.getLocale();
  342. const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
  343. const appPath = path.join(fixturesPath, 'api', 'locale-check');
  344. const args = [appPath, `--set-lang=${locale}`];
  345. if (printEnv) {
  346. args.push('--print-env');
  347. }
  348. appProcess = ChildProcess.spawn(process.execPath, args);
  349. let output = '';
  350. appProcess.stdout.on('data', (data) => { output += data; });
  351. let stderr = '';
  352. appProcess.stderr.on('data', (data) => { stderr += data; });
  353. const [code, signal] = await emittedOnce(appProcess, 'exit');
  354. if (code !== 0) {
  355. throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
  356. }
  357. output = output.replace(/(\r\n|\n|\r)/gm, '');
  358. expect(output).to.equal(result);
  359. };
  360. it('should set the locale', async () => testLocale('fr', 'fr'));
  361. it('should not set an invalid locale', async () => testLocale('asdfkl', currentLocale));
  362. const lcAll = String(process.env.LC_ALL);
  363. ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
  364. // The LC_ALL env should not be set to DOM locale string.
  365. expect(lcAll).to.not.equal(app.getLocale());
  366. });
  367. ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
  368. ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
  369. ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
  370. });
  371. describe('--remote-debugging-pipe switch', () => {
  372. it('should expose CDP via pipe', async () => {
  373. const electronPath = process.execPath;
  374. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
  375. stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
  376. }) as ChildProcess.ChildProcessWithoutNullStreams;
  377. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  378. const pipe = new PipeTransport(stdio[3], stdio[4]);
  379. const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
  380. pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
  381. const message = (await versionPromise) as any;
  382. expect(message.id).to.equal(1);
  383. expect(message.result.product).to.contain('Chrome');
  384. expect(message.result.userAgent).to.contain('Electron');
  385. });
  386. it('should override --remote-debugging-port switch', async () => {
  387. const electronPath = process.execPath;
  388. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], {
  389. stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe']
  390. }) as ChildProcess.ChildProcessWithoutNullStreams;
  391. let stderr = '';
  392. appProcess.stderr.on('data', (data: string) => { stderr += data; });
  393. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  394. const pipe = new PipeTransport(stdio[3], stdio[4]);
  395. const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
  396. pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
  397. const message = (await versionPromise) as any;
  398. expect(message.id).to.equal(1);
  399. expect(stderr).to.not.include('DevTools listening on');
  400. });
  401. it('should shut down Electron upon Browser.close CDP command', async () => {
  402. const electronPath = process.execPath;
  403. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
  404. stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
  405. }) as ChildProcess.ChildProcessWithoutNullStreams;
  406. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  407. const pipe = new PipeTransport(stdio[3], stdio[4]);
  408. pipe.send({ id: 1, method: 'Browser.close', params: {} });
  409. await new Promise(resolve => { appProcess!.on('exit', resolve); });
  410. });
  411. });
  412. describe('--remote-debugging-port switch', () => {
  413. it('should display the discovery page', (done) => {
  414. const electronPath = process.execPath;
  415. let output = '';
  416. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']);
  417. appProcess.stdout.on('data', (data) => {
  418. console.log(data);
  419. });
  420. appProcess.stderr.on('data', (data) => {
  421. console.log(data);
  422. output += data;
  423. const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
  424. if (m) {
  425. appProcess!.stderr.removeAllListeners('data');
  426. const port = m[1];
  427. http.get(`http://127.0.0.1:${port}`, (res) => {
  428. try {
  429. expect(res.statusCode).to.eql(200);
  430. expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
  431. done();
  432. } catch (e) {
  433. done(e);
  434. } finally {
  435. res.destroy();
  436. }
  437. });
  438. }
  439. });
  440. });
  441. });
  442. });
  443. describe('chromium features', () => {
  444. afterEach(closeAllWindows);
  445. describe('accessing key names also used as Node.js module names', () => {
  446. it('does not crash', (done) => {
  447. const w = new BrowserWindow({ show: false });
  448. w.webContents.once('did-finish-load', () => { done(); });
  449. w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
  450. w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
  451. });
  452. });
  453. describe('loading jquery', () => {
  454. it('does not crash', (done) => {
  455. const w = new BrowserWindow({ show: false });
  456. w.webContents.once('did-finish-load', () => { done(); });
  457. w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
  458. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
  459. });
  460. });
  461. describe('navigator.languages', () => {
  462. it('should return the system locale only', async () => {
  463. const appLocale = app.getLocale();
  464. const w = new BrowserWindow({ show: false });
  465. await w.loadURL('about:blank');
  466. const languages = await w.webContents.executeJavaScript('navigator.languages');
  467. expect(languages.length).to.be.greaterThan(0);
  468. expect(languages).to.contain(appLocale);
  469. });
  470. });
  471. describe('navigator.serviceWorker', () => {
  472. it('should register for file scheme', (done) => {
  473. const w = new BrowserWindow({
  474. show: false,
  475. webPreferences: {
  476. nodeIntegration: true,
  477. partition: 'sw-file-scheme-spec',
  478. contextIsolation: false
  479. }
  480. });
  481. w.webContents.on('ipc-message', (event, channel, message) => {
  482. if (channel === 'reload') {
  483. w.webContents.reload();
  484. } else if (channel === 'error') {
  485. done(message);
  486. } else if (channel === 'response') {
  487. expect(message).to.equal('Hello from serviceWorker!');
  488. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  489. storages: ['serviceworkers']
  490. }).then(() => done());
  491. }
  492. });
  493. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  494. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  495. });
  496. it('should register for intercepted file scheme', (done) => {
  497. const customSession = session.fromPartition('intercept-file');
  498. customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
  499. let file = url.parse(request.url).pathname!;
  500. if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
  501. const content = fs.readFileSync(path.normalize(file));
  502. const ext = path.extname(file);
  503. let type = 'text/html';
  504. if (ext === '.js') type = 'application/javascript';
  505. callback({ data: content, mimeType: type } as any);
  506. });
  507. const w = new BrowserWindow({
  508. show: false,
  509. webPreferences: {
  510. nodeIntegration: true,
  511. session: customSession,
  512. contextIsolation: false
  513. }
  514. });
  515. w.webContents.on('ipc-message', (event, channel, message) => {
  516. if (channel === 'reload') {
  517. w.webContents.reload();
  518. } else if (channel === 'error') {
  519. done(`unexpected error : ${message}`);
  520. } else if (channel === 'response') {
  521. expect(message).to.equal('Hello from serviceWorker!');
  522. customSession.clearStorageData({
  523. storages: ['serviceworkers']
  524. }).then(() => {
  525. customSession.protocol.uninterceptProtocol('file');
  526. done();
  527. });
  528. }
  529. });
  530. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  531. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  532. });
  533. it('should register for custom scheme', (done) => {
  534. const customSession = session.fromPartition('custom-scheme');
  535. const { serviceWorkerScheme } = global as any;
  536. customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => {
  537. let file = url.parse(request.url).pathname!;
  538. if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
  539. callback({ path: path.normalize(file) } as any);
  540. });
  541. const w = new BrowserWindow({
  542. show: false,
  543. webPreferences: {
  544. nodeIntegration: true,
  545. session: customSession,
  546. contextIsolation: false
  547. }
  548. });
  549. w.webContents.on('ipc-message', (event, channel, message) => {
  550. if (channel === 'reload') {
  551. w.webContents.reload();
  552. } else if (channel === 'error') {
  553. done(`unexpected error : ${message}`);
  554. } else if (channel === 'response') {
  555. expect(message).to.equal('Hello from serviceWorker!');
  556. customSession.clearStorageData({
  557. storages: ['serviceworkers']
  558. }).then(() => {
  559. customSession.protocol.uninterceptProtocol(serviceWorkerScheme);
  560. done();
  561. });
  562. }
  563. });
  564. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  565. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html'));
  566. });
  567. it('should not crash when nodeIntegration is enabled', (done) => {
  568. const w = new BrowserWindow({
  569. show: false,
  570. webPreferences: {
  571. nodeIntegration: true,
  572. nodeIntegrationInWorker: true,
  573. partition: 'sw-file-scheme-worker-spec',
  574. contextIsolation: false
  575. }
  576. });
  577. w.webContents.on('ipc-message', (event, channel, message) => {
  578. if (channel === 'reload') {
  579. w.webContents.reload();
  580. } else if (channel === 'error') {
  581. done(`unexpected error : ${message}`);
  582. } else if (channel === 'response') {
  583. expect(message).to.equal('Hello from serviceWorker!');
  584. session.fromPartition('sw-file-scheme-worker-spec').clearStorageData({
  585. storages: ['serviceworkers']
  586. }).then(() => done());
  587. }
  588. });
  589. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  590. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  591. });
  592. });
  593. describe('navigator.geolocation', () => {
  594. before(function () {
  595. if (!features.isFakeLocationProviderEnabled()) {
  596. return this.skip();
  597. }
  598. });
  599. it('returns error when permission is denied', async () => {
  600. const w = new BrowserWindow({
  601. show: false,
  602. webPreferences: {
  603. nodeIntegration: true,
  604. partition: 'geolocation-spec',
  605. contextIsolation: false
  606. }
  607. });
  608. const message = emittedOnce(w.webContents, 'ipc-message');
  609. w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
  610. if (permission === 'geolocation') {
  611. callback(false);
  612. } else {
  613. callback(true);
  614. }
  615. });
  616. w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
  617. const [, channel] = await message;
  618. expect(channel).to.equal('success', 'unexpected response from geolocation api');
  619. });
  620. });
  621. describe('web workers', () => {
  622. let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
  623. afterEach(() => {
  624. if (appProcess && !appProcess.killed) {
  625. appProcess.kill();
  626. appProcess = undefined;
  627. }
  628. });
  629. it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => {
  630. const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths');
  631. appProcess = ChildProcess.spawn(process.execPath, [appPath]);
  632. const [code] = await emittedOnce(appProcess, 'exit');
  633. expect(code).to.equal(0);
  634. });
  635. });
  636. describe('form submit', () => {
  637. let server: http.Server;
  638. let serverUrl: string;
  639. before(async () => {
  640. server = http.createServer((req, res) => {
  641. let body = '';
  642. req.on('data', (chunk) => {
  643. body += chunk;
  644. });
  645. res.setHeader('Content-Type', 'application/json');
  646. req.on('end', () => {
  647. res.end(`body:${body}`);
  648. });
  649. });
  650. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  651. serverUrl = `http://localhost:${(server.address() as any).port}`;
  652. });
  653. after(async () => {
  654. server.close();
  655. await closeAllWindows();
  656. });
  657. [true, false].forEach((isSandboxEnabled) =>
  658. describe(`sandbox=${isSandboxEnabled}`, () => {
  659. it('posts data in the same window', async () => {
  660. const w = new BrowserWindow({
  661. show: false,
  662. webPreferences: {
  663. sandbox: isSandboxEnabled
  664. }
  665. });
  666. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  667. const loadPromise = emittedOnce(w.webContents, 'did-finish-load');
  668. w.webContents.executeJavaScript(`
  669. const form = document.querySelector('form')
  670. form.action = '${serverUrl}';
  671. form.submit();
  672. `);
  673. await loadPromise;
  674. const res = await w.webContents.executeJavaScript('document.body.innerText');
  675. expect(res).to.equal('body:greeting=hello');
  676. });
  677. it('posts data to a new window with target=_blank', async () => {
  678. const w = new BrowserWindow({
  679. show: false,
  680. webPreferences: {
  681. sandbox: isSandboxEnabled
  682. }
  683. });
  684. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  685. const windowCreatedPromise = emittedOnce(app, 'browser-window-created');
  686. w.webContents.executeJavaScript(`
  687. const form = document.querySelector('form')
  688. form.action = '${serverUrl}';
  689. form.target = '_blank';
  690. form.submit();
  691. `);
  692. const [, newWin] = await windowCreatedPromise;
  693. const res = await newWin.webContents.executeJavaScript('document.body.innerText');
  694. expect(res).to.equal('body:greeting=hello');
  695. });
  696. })
  697. );
  698. });
  699. describe('window.open', () => {
  700. for (const show of [true, false]) {
  701. it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => {
  702. const w = new BrowserWindow({ show });
  703. // toggle visibility
  704. if (show) {
  705. w.hide();
  706. } else {
  707. w.show();
  708. }
  709. defer(() => { w.close(); });
  710. const newWindow = emittedOnce(w.webContents, 'new-window');
  711. w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
  712. const [,,,, options] = await newWindow;
  713. expect(options.show).to.equal(true);
  714. });
  715. }
  716. it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
  717. // NB. webSecurity is disabled because native window.open() is not
  718. // allowed to load devtools:// URLs.
  719. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } });
  720. w.loadURL('about:blank');
  721. w.webContents.executeJavaScript(`
  722. { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null }
  723. `);
  724. const [, contents] = await emittedOnce(app, 'web-contents-created');
  725. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  726. expect(typeofProcessGlobal).to.equal('undefined');
  727. });
  728. it('can disable node integration when it is enabled on the parent window with nativeWindowOpen: true', async () => {
  729. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nativeWindowOpen: true } });
  730. w.loadURL('about:blank');
  731. w.webContents.executeJavaScript(`
  732. { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null }
  733. `);
  734. const [, contents] = await emittedOnce(app, 'web-contents-created');
  735. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  736. expect(typeofProcessGlobal).to.equal('undefined');
  737. });
  738. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => {
  739. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } });
  740. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  741. const windowUrl = require('url').format({
  742. pathname: `${fixturesPath}/pages/window-no-javascript.html`,
  743. protocol: 'file',
  744. slashes: true
  745. });
  746. w.webContents.executeJavaScript(`
  747. { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null }
  748. `);
  749. const [, contents] = await emittedOnce(app, 'web-contents-created');
  750. await emittedOnce(contents, 'did-finish-load');
  751. // Click link on page
  752. contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
  753. contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
  754. const [, window] = await emittedOnce(app, 'browser-window-created');
  755. const preferences = window.webContents.getLastWebPreferences();
  756. expect(preferences.javascript).to.be.false();
  757. });
  758. it('defines a window.location getter', async () => {
  759. let targetURL: string;
  760. if (process.platform === 'win32') {
  761. targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
  762. } else {
  763. targetURL = `file://${fixturesPath}/pages/base-page.html`;
  764. }
  765. const w = new BrowserWindow({ show: false });
  766. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  767. w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
  768. const [, window] = await emittedOnce(app, 'browser-window-created');
  769. await emittedOnce(window.webContents, 'did-finish-load');
  770. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
  771. });
  772. it('defines a window.location setter', async () => {
  773. const w = new BrowserWindow({ show: false });
  774. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  775. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  776. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  777. await emittedOnce(webContents, 'did-finish-load');
  778. // When it loads, redirect
  779. w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  780. await emittedOnce(webContents, 'did-finish-load');
  781. });
  782. it('defines a window.location.href setter', async () => {
  783. const w = new BrowserWindow({ show: false });
  784. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  785. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  786. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  787. await emittedOnce(webContents, 'did-finish-load');
  788. // When it loads, redirect
  789. w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  790. await emittedOnce(webContents, 'did-finish-load');
  791. });
  792. it('open a blank page when no URL is specified', async () => {
  793. const w = new BrowserWindow({ show: false });
  794. w.loadURL('about:blank');
  795. w.webContents.executeJavaScript('{ b = window.open(); null }');
  796. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  797. await emittedOnce(webContents, 'did-finish-load');
  798. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  799. });
  800. it('open a blank page when an empty URL is specified', async () => {
  801. const w = new BrowserWindow({ show: false });
  802. w.loadURL('about:blank');
  803. w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
  804. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  805. await emittedOnce(webContents, 'did-finish-load');
  806. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  807. });
  808. it('does not throw an exception when the frameName is a built-in object property', async () => {
  809. const w = new BrowserWindow({ show: false });
  810. w.loadURL('about:blank');
  811. w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
  812. const [, , frameName] = await emittedOnce(w.webContents, 'new-window');
  813. expect(frameName).to.equal('__proto__');
  814. });
  815. it('denies custom open when nativeWindowOpen: true', async () => {
  816. const w = new BrowserWindow({
  817. show: false,
  818. webPreferences: {
  819. contextIsolation: false,
  820. nodeIntegration: true,
  821. nativeWindowOpen: true
  822. }
  823. });
  824. w.loadURL('about:blank');
  825. const previousListeners = process.listeners('uncaughtException');
  826. process.removeAllListeners('uncaughtException');
  827. try {
  828. const uncaughtException = new Promise<Error>(resolve => {
  829. process.once('uncaughtException', resolve);
  830. });
  831. expect(await w.webContents.executeJavaScript(`(${function () {
  832. const { ipc } = process._linkedBinding('electron_renderer_ipc');
  833. return ipc.sendSync(true, 'GUEST_WINDOW_MANAGER_WINDOW_OPEN', ['', '', '']);
  834. }})()`)).to.be.null();
  835. const exception = await uncaughtException;
  836. expect(exception.message).to.match(/denied: expected native window\.open/);
  837. } finally {
  838. previousListeners.forEach(l => process.on('uncaughtException', l));
  839. }
  840. });
  841. });
  842. describe('window.opener', () => {
  843. it('is null for main window', async () => {
  844. const w = new BrowserWindow({
  845. show: false,
  846. webPreferences: {
  847. nodeIntegration: true,
  848. contextIsolation: false
  849. }
  850. });
  851. w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
  852. const [, channel, opener] = await emittedOnce(w.webContents, 'ipc-message');
  853. expect(channel).to.equal('opener');
  854. expect(opener).to.equal(null);
  855. });
  856. });
  857. describe('navigator.mediaDevices', () => {
  858. afterEach(closeAllWindows);
  859. afterEach(() => {
  860. session.defaultSession.setPermissionCheckHandler(null);
  861. session.defaultSession.setPermissionRequestHandler(null);
  862. });
  863. it('can return labels of enumerated devices', async () => {
  864. const w = new BrowserWindow({ show: false });
  865. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  866. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  867. expect(labels.some((l: any) => l)).to.be.true();
  868. });
  869. it('does not return labels of enumerated devices when permission denied', async () => {
  870. session.defaultSession.setPermissionCheckHandler(() => false);
  871. const w = new BrowserWindow({ show: false });
  872. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  873. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  874. expect(labels.some((l: any) => l)).to.be.false();
  875. });
  876. it('returns the same device ids across reloads', async () => {
  877. const ses = session.fromPartition('persist:media-device-id');
  878. const w = new BrowserWindow({
  879. show: false,
  880. webPreferences: {
  881. nodeIntegration: true,
  882. session: ses,
  883. contextIsolation: false
  884. }
  885. });
  886. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  887. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  888. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  889. expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
  890. });
  891. it('can return new device id when cookie storage is cleared', async () => {
  892. const ses = session.fromPartition('persist:media-device-id');
  893. const w = new BrowserWindow({
  894. show: false,
  895. webPreferences: {
  896. nodeIntegration: true,
  897. session: ses,
  898. contextIsolation: false
  899. }
  900. });
  901. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  902. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  903. await ses.clearStorageData({ storages: ['cookies'] });
  904. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  905. expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
  906. });
  907. it('provides a securityOrigin to the request handler', async () => {
  908. session.defaultSession.setPermissionRequestHandler(
  909. (wc, permission, callback, details) => {
  910. if (details.securityOrigin !== undefined) {
  911. callback(true);
  912. } else {
  913. callback(false);
  914. }
  915. }
  916. );
  917. const w = new BrowserWindow({ show: false });
  918. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  919. const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({
  920. video: {
  921. mandatory: {
  922. chromeMediaSource: "desktop",
  923. minWidth: 1280,
  924. maxWidth: 1280,
  925. minHeight: 720,
  926. maxHeight: 720
  927. }
  928. }
  929. }).then((stream) => stream.getVideoTracks())`);
  930. expect(labels.some((l: any) => l)).to.be.true();
  931. });
  932. });
  933. describe('window.opener access', () => {
  934. const scheme = 'app';
  935. const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
  936. const httpUrl1 = `${scheme}://origin1`;
  937. const httpUrl2 = `${scheme}://origin2`;
  938. const fileBlank = `file://${fixturesPath}/pages/blank.html`;
  939. const httpBlank = `${scheme}://origin1/blank`;
  940. const table = [
  941. { parent: fileBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: false },
  942. { parent: fileBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: false },
  943. { parent: fileBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  944. { parent: fileBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: false },
  945. { parent: httpBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: false },
  946. // {parent: httpBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: false}, // can't window.open()
  947. { parent: httpBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  948. // {parent: httpBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: false}, // can't window.open()
  949. // NB. this is different from Chrome's behavior, which isolates file: urls from each other
  950. { parent: fileBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: true },
  951. { parent: fileBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: true },
  952. { parent: fileBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  953. { parent: fileBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: true },
  954. { parent: httpBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: true },
  955. { parent: httpBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: true },
  956. { parent: httpBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  957. { parent: httpBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: true },
  958. { parent: httpBlank, child: httpUrl2, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: false },
  959. { parent: httpBlank, child: httpUrl2, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: false },
  960. { parent: httpBlank, child: httpUrl2, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  961. { parent: httpBlank, child: httpUrl2, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: false }
  962. ];
  963. const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
  964. before(() => {
  965. protocol.registerFileProtocol(scheme, (request, callback) => {
  966. if (request.url.includes('blank')) {
  967. callback(`${fixturesPath}/pages/blank.html`);
  968. } else {
  969. callback(`${fixturesPath}/pages/window-opener-location.html`);
  970. }
  971. });
  972. });
  973. after(() => {
  974. protocol.unregisterProtocol(scheme);
  975. });
  976. afterEach(closeAllWindows);
  977. describe('when opened from main window', () => {
  978. for (const { parent, child, nodeIntegration, nativeWindowOpen, openerAccessible } of table) {
  979. for (const sandboxPopup of [false, true]) {
  980. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} nativeWindowOpen=${nativeWindowOpen} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  981. it(description, async () => {
  982. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, nativeWindowOpen, contextIsolation: false } });
  983. w.webContents.setWindowOpenHandler(() => ({
  984. action: 'allow',
  985. overrideBrowserWindowOptions: {
  986. webPreferences: {
  987. sandbox: sandboxPopup
  988. }
  989. }
  990. }));
  991. await w.loadURL(parent);
  992. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
  993. window.addEventListener('message', function f(e) {
  994. resolve(e.data)
  995. })
  996. window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
  997. })`);
  998. if (openerAccessible) {
  999. expect(childOpenerLocation).to.be.a('string');
  1000. } else {
  1001. expect(childOpenerLocation).to.be.null();
  1002. }
  1003. });
  1004. }
  1005. }
  1006. });
  1007. describe('when opened from <webview>', () => {
  1008. for (const { parent, child, nodeIntegration, nativeWindowOpen, openerAccessible } of table) {
  1009. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} nativeWindowOpen=${nativeWindowOpen}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  1010. // WebView erroneously allows access to the parent window when nativeWindowOpen is false.
  1011. const skip = !nativeWindowOpen && !openerAccessible;
  1012. ifit(!skip)(description, async () => {
  1013. // This test involves three contexts:
  1014. // 1. The root BrowserWindow in which the test is run,
  1015. // 2. A <webview> belonging to the root window,
  1016. // 3. A window opened by calling window.open() from within the <webview>.
  1017. // We are testing whether context (3) can access context (2) under various conditions.
  1018. // This is context (1), the base window for the test.
  1019. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false, nativeWindowOpen: false } });
  1020. await w.loadURL('about:blank');
  1021. const parentCode = `new Promise((resolve) => {
  1022. // This is context (3), a child window of the WebView.
  1023. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes")
  1024. window.addEventListener("message", e => {
  1025. resolve(e.data)
  1026. })
  1027. })`;
  1028. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  1029. // This is context (2), a WebView which will call window.open()
  1030. const webview = new WebView()
  1031. webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
  1032. webview.setAttribute('webpreferences', 'nativeWindowOpen=${nativeWindowOpen ? 'yes' : 'no'},contextIsolation=no')
  1033. webview.setAttribute('allowpopups', 'on')
  1034. webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
  1035. webview.addEventListener('dom-ready', async () => {
  1036. webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
  1037. })
  1038. document.body.appendChild(webview)
  1039. })`);
  1040. if (openerAccessible) {
  1041. expect(childOpenerLocation).to.be.a('string');
  1042. } else {
  1043. expect(childOpenerLocation).to.be.null();
  1044. }
  1045. });
  1046. }
  1047. });
  1048. });
  1049. describe('storage', () => {
  1050. describe('custom non standard schemes', () => {
  1051. const protocolName = 'storage';
  1052. let contents: WebContents;
  1053. before(() => {
  1054. protocol.registerFileProtocol(protocolName, (request, callback) => {
  1055. const parsedUrl = url.parse(request.url);
  1056. let filename;
  1057. switch (parsedUrl.pathname) {
  1058. case '/localStorage' : filename = 'local_storage.html'; break;
  1059. case '/sessionStorage' : filename = 'session_storage.html'; break;
  1060. case '/WebSQL' : filename = 'web_sql.html'; break;
  1061. case '/indexedDB' : filename = 'indexed_db.html'; break;
  1062. case '/cookie' : filename = 'cookie.html'; break;
  1063. default : filename = '';
  1064. }
  1065. callback({ path: `${fixturesPath}/pages/storage/${filename}` });
  1066. });
  1067. });
  1068. after(() => {
  1069. protocol.unregisterProtocol(protocolName);
  1070. });
  1071. beforeEach(() => {
  1072. contents = (webContents as any).create({
  1073. nodeIntegration: true,
  1074. contextIsolation: false
  1075. });
  1076. });
  1077. afterEach(() => {
  1078. (contents as any).destroy();
  1079. contents = null as any;
  1080. });
  1081. it('cannot access localStorage', async () => {
  1082. const response = emittedOnce(ipcMain, 'local-storage-response');
  1083. contents.loadURL(protocolName + '://host/localStorage');
  1084. const [, error] = await response;
  1085. expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.');
  1086. });
  1087. it('cannot access sessionStorage', async () => {
  1088. const response = emittedOnce(ipcMain, 'session-storage-response');
  1089. contents.loadURL(`${protocolName}://host/sessionStorage`);
  1090. const [, error] = await response;
  1091. expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.');
  1092. });
  1093. it('cannot access WebSQL database', async () => {
  1094. const response = emittedOnce(ipcMain, 'web-sql-response');
  1095. contents.loadURL(`${protocolName}://host/WebSQL`);
  1096. const [, error] = await response;
  1097. expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.');
  1098. });
  1099. it('cannot access indexedDB', async () => {
  1100. const response = emittedOnce(ipcMain, 'indexed-db-response');
  1101. contents.loadURL(`${protocolName}://host/indexedDB`);
  1102. const [, error] = await response;
  1103. expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.');
  1104. });
  1105. it('cannot access cookie', async () => {
  1106. const response = emittedOnce(ipcMain, 'cookie-response');
  1107. contents.loadURL(`${protocolName}://host/cookie`);
  1108. const [, error] = await response;
  1109. expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.');
  1110. });
  1111. });
  1112. describe('can be accessed', () => {
  1113. let server: http.Server;
  1114. let serverUrl: string;
  1115. let serverCrossSiteUrl: string;
  1116. before((done) => {
  1117. server = http.createServer((req, res) => {
  1118. const respond = () => {
  1119. if (req.url === '/redirect-cross-site') {
  1120. res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
  1121. res.statusCode = 302;
  1122. res.end();
  1123. } else if (req.url === '/redirected') {
  1124. res.end('<html><script>window.localStorage</script></html>');
  1125. } else {
  1126. res.end();
  1127. }
  1128. };
  1129. setTimeout(respond, 0);
  1130. });
  1131. server.listen(0, '127.0.0.1', () => {
  1132. serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  1133. serverCrossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`;
  1134. done();
  1135. });
  1136. });
  1137. after(() => {
  1138. server.close();
  1139. server = null as any;
  1140. });
  1141. afterEach(closeAllWindows);
  1142. const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
  1143. it(testTitle, async () => {
  1144. const w = new BrowserWindow({
  1145. show: false,
  1146. ...extraPreferences
  1147. });
  1148. let redirected = false;
  1149. w.webContents.on('crashed', () => {
  1150. expect.fail('renderer crashed / was killed');
  1151. });
  1152. w.webContents.on('did-redirect-navigation', (event, url) => {
  1153. expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
  1154. redirected = true;
  1155. });
  1156. await w.loadURL(`${serverUrl}/redirect-cross-site`);
  1157. expect(redirected).to.be.true('didnt redirect');
  1158. });
  1159. };
  1160. testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
  1161. testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
  1162. });
  1163. describe('enableWebSQL webpreference', () => {
  1164. const standardScheme = (global as any).standardScheme;
  1165. const origin = `${standardScheme}://fake-host`;
  1166. const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
  1167. const sqlPartition = 'web-sql-preference-test';
  1168. const sqlSession = session.fromPartition(sqlPartition);
  1169. const securityError = 'An attempt was made to break through the security policy of the user agent.';
  1170. let contents: WebContents, w: BrowserWindow;
  1171. before(() => {
  1172. sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
  1173. callback({ path: filePath });
  1174. });
  1175. });
  1176. after(() => {
  1177. sqlSession.protocol.unregisterProtocol(standardScheme);
  1178. });
  1179. afterEach(async () => {
  1180. if (contents) {
  1181. (contents as any).destroy();
  1182. contents = null as any;
  1183. }
  1184. await closeAllWindows();
  1185. (w as any) = null;
  1186. });
  1187. it('default value allows websql', async () => {
  1188. contents = (webContents as any).create({
  1189. session: sqlSession,
  1190. nodeIntegration: true,
  1191. contextIsolation: false
  1192. });
  1193. contents.loadURL(origin);
  1194. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1195. expect(error).to.be.null();
  1196. });
  1197. it('when set to false can disallow websql', async () => {
  1198. contents = (webContents as any).create({
  1199. session: sqlSession,
  1200. nodeIntegration: true,
  1201. enableWebSQL: false,
  1202. contextIsolation: false
  1203. });
  1204. contents.loadURL(origin);
  1205. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1206. expect(error).to.equal(securityError);
  1207. });
  1208. it('when set to false does not disable indexedDB', async () => {
  1209. contents = (webContents as any).create({
  1210. session: sqlSession,
  1211. nodeIntegration: true,
  1212. enableWebSQL: false,
  1213. contextIsolation: false
  1214. });
  1215. contents.loadURL(origin);
  1216. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1217. expect(error).to.equal(securityError);
  1218. const dbName = 'random';
  1219. const result = await contents.executeJavaScript(`
  1220. new Promise((resolve, reject) => {
  1221. try {
  1222. let req = window.indexedDB.open('${dbName}');
  1223. req.onsuccess = (event) => {
  1224. let db = req.result;
  1225. resolve(db.name);
  1226. }
  1227. req.onerror = (event) => { resolve(event.target.code); }
  1228. } catch (e) {
  1229. resolve(e.message);
  1230. }
  1231. });
  1232. `);
  1233. expect(result).to.equal(dbName);
  1234. });
  1235. it('child webContents can override when the embedder has allowed websql', async () => {
  1236. w = new BrowserWindow({
  1237. show: false,
  1238. webPreferences: {
  1239. nodeIntegration: true,
  1240. webviewTag: true,
  1241. session: sqlSession,
  1242. contextIsolation: false
  1243. }
  1244. });
  1245. w.webContents.loadURL(origin);
  1246. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1247. expect(error).to.be.null();
  1248. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1249. await w.webContents.executeJavaScript(`
  1250. new Promise((resolve, reject) => {
  1251. const webview = new WebView();
  1252. webview.setAttribute('src', '${origin}');
  1253. webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no');
  1254. webview.setAttribute('partition', '${sqlPartition}');
  1255. webview.setAttribute('nodeIntegration', 'on');
  1256. document.body.appendChild(webview);
  1257. webview.addEventListener('dom-ready', () => resolve());
  1258. });
  1259. `);
  1260. const [, childError] = await webviewResult;
  1261. expect(childError).to.equal(securityError);
  1262. });
  1263. it('child webContents cannot override when the embedder has disallowed websql', async () => {
  1264. w = new BrowserWindow({
  1265. show: false,
  1266. webPreferences: {
  1267. nodeIntegration: true,
  1268. enableWebSQL: false,
  1269. webviewTag: true,
  1270. session: sqlSession,
  1271. contextIsolation: false
  1272. }
  1273. });
  1274. w.webContents.loadURL('data:text/html,<html></html>');
  1275. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1276. await w.webContents.executeJavaScript(`
  1277. new Promise((resolve, reject) => {
  1278. const webview = new WebView();
  1279. webview.setAttribute('src', '${origin}');
  1280. webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
  1281. webview.setAttribute('partition', '${sqlPartition}');
  1282. webview.setAttribute('nodeIntegration', 'on');
  1283. document.body.appendChild(webview);
  1284. webview.addEventListener('dom-ready', () => resolve());
  1285. });
  1286. `);
  1287. const [, childError] = await webviewResult;
  1288. expect(childError).to.equal(securityError);
  1289. });
  1290. it('child webContents can use websql when the embedder has allowed websql', async () => {
  1291. w = new BrowserWindow({
  1292. show: false,
  1293. webPreferences: {
  1294. nodeIntegration: true,
  1295. webviewTag: true,
  1296. session: sqlSession,
  1297. contextIsolation: false
  1298. }
  1299. });
  1300. w.webContents.loadURL(origin);
  1301. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1302. expect(error).to.be.null();
  1303. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1304. await w.webContents.executeJavaScript(`
  1305. new Promise((resolve, reject) => {
  1306. const webview = new WebView();
  1307. webview.setAttribute('src', '${origin}');
  1308. webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
  1309. webview.setAttribute('partition', '${sqlPartition}');
  1310. webview.setAttribute('nodeIntegration', 'on');
  1311. document.body.appendChild(webview);
  1312. webview.addEventListener('dom-ready', () => resolve());
  1313. });
  1314. `);
  1315. const [, childError] = await webviewResult;
  1316. expect(childError).to.be.null();
  1317. });
  1318. });
  1319. });
  1320. ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
  1321. const pdfSource = url.format({
  1322. pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'),
  1323. protocol: 'file',
  1324. slashes: true
  1325. });
  1326. it('successfully loads a PDF file', async () => {
  1327. const w = new BrowserWindow({ show: false });
  1328. w.loadURL(pdfSource);
  1329. await emittedOnce(w.webContents, 'did-finish-load');
  1330. });
  1331. it('opens when loading a pdf resource as top level navigation', async () => {
  1332. const w = new BrowserWindow({ show: false });
  1333. w.loadURL(pdfSource);
  1334. const [, contents] = await emittedOnce(app, 'web-contents-created');
  1335. await emittedOnce(contents, 'did-navigate');
  1336. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1337. });
  1338. it('opens when loading a pdf resource in a iframe', async () => {
  1339. const w = new BrowserWindow({ show: false });
  1340. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
  1341. const [, contents] = await emittedOnce(app, 'web-contents-created');
  1342. await emittedOnce(contents, 'did-navigate');
  1343. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1344. });
  1345. });
  1346. describe('window.history', () => {
  1347. describe('window.history.pushState', () => {
  1348. it('should push state after calling history.pushState() from the same url', async () => {
  1349. const w = new BrowserWindow({ show: false });
  1350. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1351. // History should have current page by now.
  1352. expect((w.webContents as any).length()).to.equal(1);
  1353. const waitCommit = emittedOnce(w.webContents, 'navigation-entry-committed');
  1354. w.webContents.executeJavaScript('window.history.pushState({}, "")');
  1355. await waitCommit;
  1356. // Initial page + pushed state.
  1357. expect((w.webContents as any).length()).to.equal(2);
  1358. });
  1359. });
  1360. });
  1361. describe('chrome://media-internals', () => {
  1362. it('loads the page successfully', async () => {
  1363. const w = new BrowserWindow({ show: false });
  1364. w.loadURL('chrome://media-internals');
  1365. const pageExists = await w.webContents.executeJavaScript(
  1366. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1367. );
  1368. expect(pageExists).to.be.true();
  1369. });
  1370. });
  1371. describe('chrome://webrtc-internals', () => {
  1372. it('loads the page successfully', async () => {
  1373. const w = new BrowserWindow({ show: false });
  1374. w.loadURL('chrome://webrtc-internals');
  1375. const pageExists = await w.webContents.executeJavaScript(
  1376. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1377. );
  1378. expect(pageExists).to.be.true();
  1379. });
  1380. });
  1381. describe('document.hasFocus', () => {
  1382. it('has correct value when multiple windows are opened', async () => {
  1383. const w1 = new BrowserWindow({ show: true });
  1384. const w2 = new BrowserWindow({ show: true });
  1385. const w3 = new BrowserWindow({ show: false });
  1386. await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1387. await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1388. await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1389. expect(webContents.getFocusedWebContents().id).to.equal(w2.webContents.id);
  1390. let focus = false;
  1391. focus = await w1.webContents.executeJavaScript(
  1392. 'document.hasFocus()'
  1393. );
  1394. expect(focus).to.be.false();
  1395. focus = await w2.webContents.executeJavaScript(
  1396. 'document.hasFocus()'
  1397. );
  1398. expect(focus).to.be.true();
  1399. focus = await w3.webContents.executeJavaScript(
  1400. 'document.hasFocus()'
  1401. );
  1402. expect(focus).to.be.false();
  1403. });
  1404. });
  1405. describe('navigator.userAgentData', () => {
  1406. // These tests are done on an http server because navigator.userAgentData
  1407. // requires a secure context.
  1408. let server: http.Server;
  1409. let serverUrl: string;
  1410. before(async () => {
  1411. server = http.createServer((req, res) => {
  1412. res.setHeader('Content-Type', 'text/html');
  1413. res.end('');
  1414. });
  1415. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1416. serverUrl = `http://localhost:${(server.address() as any).port}`;
  1417. });
  1418. after(() => {
  1419. server.close();
  1420. });
  1421. describe('is not empty', () => {
  1422. it('by default', async () => {
  1423. const w = new BrowserWindow({ show: false });
  1424. await w.loadURL(serverUrl);
  1425. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1426. expect(platform).not.to.be.empty();
  1427. });
  1428. it('when there is a session-wide UA override', async () => {
  1429. const ses = session.fromPartition(`${Math.random()}`);
  1430. ses.setUserAgent('foobar');
  1431. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  1432. await w.loadURL(serverUrl);
  1433. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1434. expect(platform).not.to.be.empty();
  1435. });
  1436. it('when there is a WebContents-specific UA override', async () => {
  1437. const w = new BrowserWindow({ show: false });
  1438. w.webContents.setUserAgent('foo');
  1439. await w.loadURL(serverUrl);
  1440. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1441. expect(platform).not.to.be.empty();
  1442. });
  1443. it('when there is a WebContents-specific UA override at load time', async () => {
  1444. const w = new BrowserWindow({ show: false });
  1445. await w.loadURL(serverUrl, {
  1446. userAgent: 'foo'
  1447. });
  1448. const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
  1449. expect(platform).not.to.be.empty();
  1450. });
  1451. });
  1452. describe('brand list', () => {
  1453. it('contains chromium', async () => {
  1454. const w = new BrowserWindow({ show: false });
  1455. await w.loadURL(serverUrl);
  1456. const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands');
  1457. expect(brands.map((b: any) => b.brand)).to.include('Chromium');
  1458. });
  1459. });
  1460. });
  1461. });
  1462. describe('font fallback', () => {
  1463. async function getRenderedFonts (html: string) {
  1464. const w = new BrowserWindow({ show: false });
  1465. try {
  1466. await w.loadURL(`data:text/html,${html}`);
  1467. w.webContents.debugger.attach();
  1468. const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
  1469. const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
  1470. await sendCommand('CSS.enable');
  1471. const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
  1472. return fonts;
  1473. } finally {
  1474. w.close();
  1475. }
  1476. }
  1477. it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
  1478. const html = '<body style="font-family: sans-serif">test</body>';
  1479. const fonts = await getRenderedFonts(html);
  1480. expect(fonts).to.be.an('array');
  1481. expect(fonts).to.have.length(1);
  1482. if (process.platform === 'win32') {
  1483. expect(fonts[0].familyName).to.equal('Arial');
  1484. } else if (process.platform === 'darwin') {
  1485. expect(fonts[0].familyName).to.equal('Helvetica');
  1486. } else if (process.platform === 'linux') {
  1487. expect(fonts[0].familyName).to.equal('DejaVu Sans');
  1488. } // I think this depends on the distro? We don't specify a default.
  1489. });
  1490. ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
  1491. const html = `
  1492. <html lang="ja-JP">
  1493. <head>
  1494. <meta charset="utf-8" />
  1495. </head>
  1496. <body style="font-family: sans-serif">test 智史</body>
  1497. </html>
  1498. `;
  1499. const fonts = await getRenderedFonts(html);
  1500. expect(fonts).to.be.an('array');
  1501. expect(fonts).to.have.length(1);
  1502. 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'); }
  1503. });
  1504. });
  1505. describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
  1506. const fullscreenChildHtml = promisify(fs.readFile)(
  1507. path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
  1508. );
  1509. let w: BrowserWindow, server: http.Server;
  1510. before(() => {
  1511. server = http.createServer(async (_req, res) => {
  1512. res.writeHead(200, { 'Content-Type': 'text/html' });
  1513. res.write(await fullscreenChildHtml);
  1514. res.end();
  1515. });
  1516. server.listen(8989, '127.0.0.1');
  1517. });
  1518. beforeEach(() => {
  1519. w = new BrowserWindow({
  1520. show: true,
  1521. fullscreen: true,
  1522. webPreferences: {
  1523. nodeIntegration: true,
  1524. nodeIntegrationInSubFrames: true,
  1525. contextIsolation: false
  1526. }
  1527. });
  1528. });
  1529. afterEach(async () => {
  1530. await closeAllWindows();
  1531. (w as any) = null;
  1532. server.close();
  1533. });
  1534. it('can fullscreen from out-of-process iframes (OOPIFs)', async () => {
  1535. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  1536. const html =
  1537. '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>';
  1538. w.loadURL(`data:text/html,${html}`);
  1539. await fullscreenChange;
  1540. const fullscreenWidth = await w.webContents.executeJavaScript(
  1541. "document.querySelector('iframe').offsetWidth"
  1542. );
  1543. expect(fullscreenWidth > 0).to.be.true();
  1544. await w.webContents.executeJavaScript(
  1545. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  1546. );
  1547. await delay(500);
  1548. const width = await w.webContents.executeJavaScript(
  1549. "document.querySelector('iframe').offsetWidth"
  1550. );
  1551. expect(width).to.equal(0);
  1552. });
  1553. it('can fullscreen from in-process iframes', async () => {
  1554. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  1555. w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
  1556. await fullscreenChange;
  1557. const fullscreenWidth = await w.webContents.executeJavaScript(
  1558. "document.querySelector('iframe').offsetWidth"
  1559. );
  1560. expect(fullscreenWidth > 0).to.true();
  1561. await w.webContents.executeJavaScript('document.exitFullscreen()');
  1562. const width = await w.webContents.executeJavaScript(
  1563. "document.querySelector('iframe').offsetWidth"
  1564. );
  1565. expect(width).to.equal(0);
  1566. });
  1567. });
  1568. describe('navigator.serial', () => {
  1569. let w: BrowserWindow;
  1570. before(async () => {
  1571. w = new BrowserWindow({
  1572. show: false
  1573. });
  1574. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1575. });
  1576. const getPorts: any = () => {
  1577. return w.webContents.executeJavaScript(`
  1578. navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
  1579. `, true);
  1580. };
  1581. after(closeAllWindows);
  1582. afterEach(() => {
  1583. session.defaultSession.setPermissionCheckHandler(null);
  1584. session.defaultSession.removeAllListeners('select-serial-port');
  1585. });
  1586. it('does not return a port if select-serial-port event is not defined', async () => {
  1587. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1588. const port = await getPorts();
  1589. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1590. });
  1591. it('does not return a port when permission denied', async () => {
  1592. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1593. callback(portList[0].portId);
  1594. });
  1595. session.defaultSession.setPermissionCheckHandler(() => false);
  1596. const port = await getPorts();
  1597. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1598. });
  1599. it('does not crash when select-serial-port is called with an invalid port', async () => {
  1600. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1601. callback('i-do-not-exist');
  1602. });
  1603. const port = await getPorts();
  1604. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1605. });
  1606. it('returns a port when select-serial-port event is defined', async () => {
  1607. let havePorts = false;
  1608. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1609. if (portList.length > 0) {
  1610. havePorts = true;
  1611. callback(portList[0].portId);
  1612. } else {
  1613. callback('');
  1614. }
  1615. });
  1616. const port = await getPorts();
  1617. if (havePorts) {
  1618. expect(port).to.equal('[object SerialPort]');
  1619. } else {
  1620. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1621. }
  1622. });
  1623. it('navigator.serial.getPorts() returns values', async () => {
  1624. let havePorts = false;
  1625. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1626. if (portList.length > 0) {
  1627. havePorts = true;
  1628. callback(portList[0].portId);
  1629. } else {
  1630. callback('');
  1631. }
  1632. });
  1633. await getPorts();
  1634. if (havePorts) {
  1635. const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
  1636. expect(grantedPorts).to.not.be.empty();
  1637. }
  1638. });
  1639. });
  1640. describe('navigator.clipboard', () => {
  1641. let w: BrowserWindow;
  1642. before(async () => {
  1643. w = new BrowserWindow({
  1644. webPreferences: {
  1645. enableBlinkFeatures: 'Serial'
  1646. }
  1647. });
  1648. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1649. });
  1650. const readClipboard: any = () => {
  1651. return w.webContents.executeJavaScript(`
  1652. navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
  1653. `, true);
  1654. };
  1655. after(closeAllWindows);
  1656. afterEach(() => {
  1657. session.defaultSession.setPermissionRequestHandler(null);
  1658. });
  1659. it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
  1660. const clipboard = await readClipboard();
  1661. expect(clipboard).to.not.equal('Read permission denied.');
  1662. });
  1663. it('returns an error when permission denied', async () => {
  1664. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  1665. if (permission === 'clipboard-read') {
  1666. callback(false);
  1667. } else {
  1668. callback(true);
  1669. }
  1670. });
  1671. const clipboard = await readClipboard();
  1672. expect(clipboard).to.equal('Read permission denied.');
  1673. });
  1674. it('returns clipboard contents when permission is granted', async () => {
  1675. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  1676. if (permission === 'clipboard-read') {
  1677. callback(true);
  1678. } else {
  1679. callback(false);
  1680. }
  1681. });
  1682. const clipboard = await readClipboard();
  1683. expect(clipboard).to.not.equal('Read permission denied.');
  1684. });
  1685. });
  1686. ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
  1687. let w: BrowserWindow;
  1688. const expectedBadgeCount = 42;
  1689. const fireAppBadgeAction: any = (action: string, value: any) => {
  1690. return w.webContents.executeJavaScript(`
  1691. navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
  1692. };
  1693. // For some reason on macOS changing the badge count doesn't happen right away, so wait
  1694. // until it changes.
  1695. async function waitForBadgeCount (value: number) {
  1696. let badgeCount = app.getBadgeCount();
  1697. while (badgeCount !== value) {
  1698. await new Promise(resolve => setTimeout(resolve, 10));
  1699. badgeCount = app.getBadgeCount();
  1700. }
  1701. return badgeCount;
  1702. }
  1703. describe('in the renderer', () => {
  1704. before(async () => {
  1705. w = new BrowserWindow({
  1706. show: false
  1707. });
  1708. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1709. });
  1710. after(() => {
  1711. app.badgeCount = 0;
  1712. closeAllWindows();
  1713. });
  1714. it('setAppBadge can set a numerical value', async () => {
  1715. const result = await fireAppBadgeAction('set', expectedBadgeCount);
  1716. expect(result).to.equal('success');
  1717. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1718. });
  1719. it('setAppBadge can set an empty(dot) value', async () => {
  1720. const result = await fireAppBadgeAction('set');
  1721. expect(result).to.equal('success');
  1722. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  1723. });
  1724. it('clearAppBadge can clear a value', async () => {
  1725. let result = await fireAppBadgeAction('set', expectedBadgeCount);
  1726. expect(result).to.equal('success');
  1727. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1728. result = await fireAppBadgeAction('clear');
  1729. expect(result).to.equal('success');
  1730. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  1731. });
  1732. });
  1733. describe('in a service worker', () => {
  1734. beforeEach(async () => {
  1735. w = new BrowserWindow({
  1736. show: false,
  1737. webPreferences: {
  1738. nodeIntegration: true,
  1739. partition: 'sw-file-scheme-spec',
  1740. contextIsolation: false
  1741. }
  1742. });
  1743. });
  1744. afterEach(() => {
  1745. app.badgeCount = 0;
  1746. closeAllWindows();
  1747. });
  1748. it('setAppBadge can be called in a ServiceWorker', (done) => {
  1749. w.webContents.on('ipc-message', (event, channel, message) => {
  1750. if (channel === 'reload') {
  1751. w.webContents.reload();
  1752. } else if (channel === 'error') {
  1753. done(message);
  1754. } else if (channel === 'response') {
  1755. expect(message).to.equal('SUCCESS setting app badge');
  1756. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1757. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  1758. storages: ['serviceworkers']
  1759. }).then(() => done());
  1760. }
  1761. });
  1762. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  1763. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
  1764. });
  1765. it('clearAppBadge can be called in a ServiceWorker', (done) => {
  1766. w.webContents.on('ipc-message', (event, channel, message) => {
  1767. if (channel === 'reload') {
  1768. w.webContents.reload();
  1769. } else if (channel === 'setAppBadge') {
  1770. expect(message).to.equal('SUCCESS setting app badge');
  1771. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1772. } else if (channel === 'error') {
  1773. done(message);
  1774. } else if (channel === 'response') {
  1775. expect(message).to.equal('SUCCESS clearing app badge');
  1776. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1777. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  1778. storages: ['serviceworkers']
  1779. }).then(() => done());
  1780. }
  1781. });
  1782. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  1783. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
  1784. });
  1785. });
  1786. });
  1787. describe('navigator.bluetooth', () => {
  1788. let w: BrowserWindow;
  1789. before(async () => {
  1790. w = new BrowserWindow({
  1791. show: false,
  1792. webPreferences: {
  1793. enableBlinkFeatures: 'WebBluetooth'
  1794. }
  1795. });
  1796. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1797. });
  1798. after(closeAllWindows);
  1799. it('can request bluetooth devices', async () => {
  1800. const bluetooth = await w.webContents.executeJavaScript(`
  1801. navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
  1802. expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
  1803. });
  1804. });
  1805. describe('navigator.hid', () => {
  1806. let w: BrowserWindow;
  1807. let server: http.Server;
  1808. let serverUrl: string;
  1809. before(async () => {
  1810. w = new BrowserWindow({
  1811. show: false
  1812. });
  1813. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1814. server = http.createServer((req, res) => {
  1815. res.setHeader('Content-Type', 'text/html');
  1816. res.end('<body>');
  1817. });
  1818. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1819. serverUrl = `http://localhost:${(server.address() as any).port}`;
  1820. });
  1821. const getDevices: any = () => {
  1822. return w.webContents.executeJavaScript(`
  1823. navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
  1824. `, true);
  1825. };
  1826. after(() => {
  1827. server.close();
  1828. closeAllWindows();
  1829. });
  1830. afterEach(() => {
  1831. session.defaultSession.setPermissionCheckHandler(null);
  1832. session.defaultSession.setDevicePermissionHandler(null);
  1833. session.defaultSession.removeAllListeners('select-hid-device');
  1834. });
  1835. it('does not return a device if select-hid-device event is not defined', async () => {
  1836. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1837. const device = await getDevices();
  1838. expect(device).to.equal('');
  1839. });
  1840. it('does not return a device when permission denied', async () => {
  1841. let selectFired = false;
  1842. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  1843. selectFired = true;
  1844. callback();
  1845. });
  1846. session.defaultSession.setPermissionCheckHandler(() => false);
  1847. const device = await getDevices();
  1848. expect(selectFired).to.be.false();
  1849. expect(device).to.equal('');
  1850. });
  1851. it('returns a device when select-hid-device event is defined', async () => {
  1852. let haveDevices = false;
  1853. let selectFired = false;
  1854. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  1855. expect(details.frame).to.have.ownProperty('frameTreeNodeId').that.is.a('number');
  1856. selectFired = true;
  1857. if (details.deviceList.length > 0) {
  1858. haveDevices = true;
  1859. callback(details.deviceList[0].deviceId);
  1860. } else {
  1861. callback();
  1862. }
  1863. });
  1864. const device = await getDevices();
  1865. expect(selectFired).to.be.true();
  1866. if (haveDevices) {
  1867. expect(device).to.contain('[object HIDDevice]');
  1868. } else {
  1869. expect(device).to.equal('');
  1870. }
  1871. if (process.arch === 'arm64' || process.arch === 'arm') {
  1872. // arm CI returns HID devices - this block may need to change if CI hardware changes.
  1873. expect(haveDevices).to.be.true();
  1874. // Verify that navigation will clear device permissions
  1875. const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  1876. expect(grantedDevices).to.not.be.empty();
  1877. w.loadURL(serverUrl);
  1878. const [,,,,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-navigate');
  1879. const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
  1880. expect(frame).to.not.be.empty();
  1881. if (frame) {
  1882. const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
  1883. expect(grantedDevicesOnNewPage).to.be.empty();
  1884. }
  1885. }
  1886. });
  1887. it('returns a device when DevicePermissionHandler is defined', async () => {
  1888. let haveDevices = false;
  1889. let selectFired = false;
  1890. let gotDevicePerms = false;
  1891. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  1892. selectFired = true;
  1893. if (details.deviceList.length > 0) {
  1894. const foundDevice = details.deviceList.find((device) => {
  1895. if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
  1896. haveDevices = true;
  1897. return true;
  1898. }
  1899. });
  1900. if (foundDevice) {
  1901. callback(foundDevice.deviceId);
  1902. return;
  1903. }
  1904. }
  1905. callback();
  1906. });
  1907. session.defaultSession.setDevicePermissionHandler(() => {
  1908. gotDevicePerms = true;
  1909. return true;
  1910. });
  1911. await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
  1912. const device = await getDevices();
  1913. expect(selectFired).to.be.true();
  1914. if (haveDevices) {
  1915. expect(device).to.contain('[object HIDDevice]');
  1916. expect(gotDevicePerms).to.be.true();
  1917. } else {
  1918. expect(device).to.equal('');
  1919. }
  1920. });
  1921. });