chromium-spec.ts 79 KB

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