chromium-spec.ts 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040
  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. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  717. w.loadURL('about:blank');
  718. w.webContents.executeJavaScript(`
  719. { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null }
  720. `);
  721. const [, contents] = await emittedOnce(app, 'web-contents-created');
  722. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  723. expect(typeofProcessGlobal).to.equal('undefined');
  724. });
  725. it('can disable node integration when it is enabled on the parent window with nativeWindowOpen: true', async () => {
  726. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nativeWindowOpen: true } });
  727. w.loadURL('about:blank');
  728. w.webContents.executeJavaScript(`
  729. { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null }
  730. `);
  731. const [, contents] = await emittedOnce(app, 'web-contents-created');
  732. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  733. expect(typeofProcessGlobal).to.equal('undefined');
  734. });
  735. it('disables JavaScript when it is disabled on the parent window', async () => {
  736. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  737. w.webContents.loadURL('about:blank');
  738. const windowUrl = require('url').format({
  739. pathname: `${fixturesPath}/pages/window-no-javascript.html`,
  740. protocol: 'file',
  741. slashes: true
  742. });
  743. w.webContents.executeJavaScript(`
  744. { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null }
  745. `);
  746. const [, contents] = await emittedOnce(app, 'web-contents-created');
  747. await emittedOnce(contents, 'did-finish-load');
  748. // Click link on page
  749. contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
  750. contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
  751. const [, window] = await emittedOnce(app, 'browser-window-created');
  752. const preferences = window.webContents.getLastWebPreferences();
  753. expect(preferences.javascript).to.be.false();
  754. });
  755. it('defines a window.location getter', async () => {
  756. let targetURL: string;
  757. if (process.platform === 'win32') {
  758. targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
  759. } else {
  760. targetURL = `file://${fixturesPath}/pages/base-page.html`;
  761. }
  762. const w = new BrowserWindow({ show: false });
  763. w.loadURL('about:blank');
  764. w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
  765. const [, window] = await emittedOnce(app, 'browser-window-created');
  766. await emittedOnce(window.webContents, 'did-finish-load');
  767. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
  768. });
  769. it('defines a window.location setter', async () => {
  770. const w = new BrowserWindow({ show: false });
  771. w.loadURL('about:blank');
  772. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  773. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  774. await emittedOnce(webContents, 'did-finish-load');
  775. // When it loads, redirect
  776. w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  777. await emittedOnce(webContents, 'did-finish-load');
  778. });
  779. it('defines a window.location.href setter', async () => {
  780. const w = new BrowserWindow({ show: false });
  781. w.loadURL('about:blank');
  782. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  783. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  784. await emittedOnce(webContents, 'did-finish-load');
  785. // When it loads, redirect
  786. w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  787. await emittedOnce(webContents, 'did-finish-load');
  788. });
  789. it('open a blank page when no 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('open a blank page when an empty URL is specified', async () => {
  798. const w = new BrowserWindow({ show: false });
  799. w.loadURL('about:blank');
  800. w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
  801. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  802. await emittedOnce(webContents, 'did-finish-load');
  803. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  804. });
  805. it('does not throw an exception when the frameName is a built-in object property', async () => {
  806. const w = new BrowserWindow({ show: false });
  807. w.loadURL('about:blank');
  808. w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
  809. const [, , frameName] = await emittedOnce(w.webContents, 'new-window');
  810. expect(frameName).to.equal('__proto__');
  811. });
  812. it('denies custom open when nativeWindowOpen: true', async () => {
  813. const w = new BrowserWindow({
  814. show: false,
  815. webPreferences: {
  816. contextIsolation: false,
  817. nodeIntegration: true,
  818. nativeWindowOpen: true
  819. }
  820. });
  821. w.loadURL('about:blank');
  822. const previousListeners = process.listeners('uncaughtException');
  823. process.removeAllListeners('uncaughtException');
  824. try {
  825. const uncaughtException = new Promise<Error>(resolve => {
  826. process.once('uncaughtException', resolve);
  827. });
  828. expect(await w.webContents.executeJavaScript(`(${function () {
  829. const { ipc } = process._linkedBinding('electron_renderer_ipc');
  830. return ipc.sendSync(true, 'GUEST_WINDOW_MANAGER_WINDOW_OPEN', ['', '', '']);
  831. }})()`)).to.be.null();
  832. const exception = await uncaughtException;
  833. expect(exception.message).to.match(/denied: expected native window\.open/);
  834. } finally {
  835. previousListeners.forEach(l => process.on('uncaughtException', l));
  836. }
  837. });
  838. });
  839. describe('window.opener', () => {
  840. it('is null for main window', async () => {
  841. const w = new BrowserWindow({
  842. show: false,
  843. webPreferences: {
  844. nodeIntegration: true,
  845. contextIsolation: false
  846. }
  847. });
  848. w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
  849. const [, channel, opener] = await emittedOnce(w.webContents, 'ipc-message');
  850. expect(channel).to.equal('opener');
  851. expect(opener).to.equal(null);
  852. });
  853. });
  854. describe('navigator.mediaDevices', () => {
  855. afterEach(closeAllWindows);
  856. afterEach(() => {
  857. session.defaultSession.setPermissionCheckHandler(null);
  858. session.defaultSession.setPermissionRequestHandler(null);
  859. });
  860. it('can return labels of enumerated devices', async () => {
  861. const w = new BrowserWindow({ show: false });
  862. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  863. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  864. expect(labels.some((l: any) => l)).to.be.true();
  865. });
  866. it('does not return labels of enumerated devices when permission denied', async () => {
  867. session.defaultSession.setPermissionCheckHandler(() => false);
  868. const w = new BrowserWindow({ show: false });
  869. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  870. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  871. expect(labels.some((l: any) => l)).to.be.false();
  872. });
  873. it('returns the same device ids across reloads', async () => {
  874. const ses = session.fromPartition('persist:media-device-id');
  875. const w = new BrowserWindow({
  876. show: false,
  877. webPreferences: {
  878. nodeIntegration: true,
  879. session: ses,
  880. contextIsolation: false
  881. }
  882. });
  883. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  884. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  885. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  886. expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
  887. });
  888. it('can return new device id when cookie storage is cleared', async () => {
  889. const ses = session.fromPartition('persist:media-device-id');
  890. const w = new BrowserWindow({
  891. show: false,
  892. webPreferences: {
  893. nodeIntegration: true,
  894. session: ses,
  895. contextIsolation: false
  896. }
  897. });
  898. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  899. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  900. await ses.clearStorageData({ storages: ['cookies'] });
  901. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  902. expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
  903. });
  904. it('provides a securityOrigin to the request handler', async () => {
  905. session.defaultSession.setPermissionRequestHandler(
  906. (wc, permission, callback, details) => {
  907. if (details.securityOrigin !== undefined) {
  908. callback(true);
  909. } else {
  910. callback(false);
  911. }
  912. }
  913. );
  914. const w = new BrowserWindow({ show: false });
  915. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  916. const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({
  917. video: {
  918. mandatory: {
  919. chromeMediaSource: "desktop",
  920. minWidth: 1280,
  921. maxWidth: 1280,
  922. minHeight: 720,
  923. maxHeight: 720
  924. }
  925. }
  926. }).then((stream) => stream.getVideoTracks())`);
  927. expect(labels.some((l: any) => l)).to.be.true();
  928. });
  929. });
  930. describe('window.opener access', () => {
  931. const scheme = 'app';
  932. const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
  933. const httpUrl1 = `${scheme}://origin1`;
  934. const httpUrl2 = `${scheme}://origin2`;
  935. const fileBlank = `file://${fixturesPath}/pages/blank.html`;
  936. const httpBlank = `${scheme}://origin1/blank`;
  937. const table = [
  938. { parent: fileBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: false },
  939. { parent: fileBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: false },
  940. { parent: fileBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  941. { parent: fileBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: false },
  942. { parent: httpBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: false },
  943. // {parent: httpBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: false}, // can't window.open()
  944. { parent: httpBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  945. // {parent: httpBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: false}, // can't window.open()
  946. // NB. this is different from Chrome's behavior, which isolates file: urls from each other
  947. { parent: fileBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: true },
  948. { parent: fileBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: true },
  949. { parent: fileBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  950. { parent: fileBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: true },
  951. { parent: httpBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: true },
  952. { parent: httpBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: true },
  953. { parent: httpBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  954. { parent: httpBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: true },
  955. { parent: httpBlank, child: httpUrl2, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: false },
  956. { parent: httpBlank, child: httpUrl2, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: false },
  957. { parent: httpBlank, child: httpUrl2, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  958. { parent: httpBlank, child: httpUrl2, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: false }
  959. ];
  960. const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
  961. before(() => {
  962. protocol.registerFileProtocol(scheme, (request, callback) => {
  963. if (request.url.includes('blank')) {
  964. callback(`${fixturesPath}/pages/blank.html`);
  965. } else {
  966. callback(`${fixturesPath}/pages/window-opener-location.html`);
  967. }
  968. });
  969. });
  970. after(() => {
  971. protocol.unregisterProtocol(scheme);
  972. });
  973. afterEach(closeAllWindows);
  974. describe('when opened from main window', () => {
  975. for (const { parent, child, nodeIntegration, nativeWindowOpen, openerAccessible } of table) {
  976. for (const sandboxPopup of [false, true]) {
  977. 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`;
  978. it(description, async () => {
  979. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, nativeWindowOpen, contextIsolation: false } });
  980. w.webContents.setWindowOpenHandler(() => ({
  981. action: 'allow',
  982. overrideBrowserWindowOptions: {
  983. webPreferences: {
  984. sandbox: sandboxPopup
  985. }
  986. }
  987. }));
  988. await w.loadURL(parent);
  989. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
  990. window.addEventListener('message', function f(e) {
  991. resolve(e.data)
  992. })
  993. window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
  994. })`);
  995. if (openerAccessible) {
  996. expect(childOpenerLocation).to.be.a('string');
  997. } else {
  998. expect(childOpenerLocation).to.be.null();
  999. }
  1000. });
  1001. }
  1002. }
  1003. });
  1004. describe('when opened from <webview>', () => {
  1005. for (const { parent, child, nodeIntegration, nativeWindowOpen, openerAccessible } of table) {
  1006. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} nativeWindowOpen=${nativeWindowOpen}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  1007. // WebView erroneously allows access to the parent window when nativeWindowOpen is false.
  1008. const skip = !nativeWindowOpen && !openerAccessible;
  1009. ifit(!skip)(description, async () => {
  1010. // This test involves three contexts:
  1011. // 1. The root BrowserWindow in which the test is run,
  1012. // 2. A <webview> belonging to the root window,
  1013. // 3. A window opened by calling window.open() from within the <webview>.
  1014. // We are testing whether context (3) can access context (2) under various conditions.
  1015. // This is context (1), the base window for the test.
  1016. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
  1017. await w.loadURL('about:blank');
  1018. const parentCode = `new Promise((resolve) => {
  1019. // This is context (3), a child window of the WebView.
  1020. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes")
  1021. window.addEventListener("message", e => {
  1022. resolve(e.data)
  1023. })
  1024. })`;
  1025. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  1026. // This is context (2), a WebView which will call window.open()
  1027. const webview = new WebView()
  1028. webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
  1029. webview.setAttribute('webpreferences', 'nativeWindowOpen=${nativeWindowOpen ? 'yes' : 'no'},contextIsolation=no')
  1030. webview.setAttribute('allowpopups', 'on')
  1031. webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
  1032. webview.addEventListener('dom-ready', async () => {
  1033. webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
  1034. })
  1035. document.body.appendChild(webview)
  1036. })`);
  1037. if (openerAccessible) {
  1038. expect(childOpenerLocation).to.be.a('string');
  1039. } else {
  1040. expect(childOpenerLocation).to.be.null();
  1041. }
  1042. });
  1043. }
  1044. });
  1045. });
  1046. describe('storage', () => {
  1047. describe('custom non standard schemes', () => {
  1048. const protocolName = 'storage';
  1049. let contents: WebContents;
  1050. before(() => {
  1051. protocol.registerFileProtocol(protocolName, (request, callback) => {
  1052. const parsedUrl = url.parse(request.url);
  1053. let filename;
  1054. switch (parsedUrl.pathname) {
  1055. case '/localStorage' : filename = 'local_storage.html'; break;
  1056. case '/sessionStorage' : filename = 'session_storage.html'; break;
  1057. case '/WebSQL' : filename = 'web_sql.html'; break;
  1058. case '/indexedDB' : filename = 'indexed_db.html'; break;
  1059. case '/cookie' : filename = 'cookie.html'; break;
  1060. default : filename = '';
  1061. }
  1062. callback({ path: `${fixturesPath}/pages/storage/${filename}` });
  1063. });
  1064. });
  1065. after(() => {
  1066. protocol.unregisterProtocol(protocolName);
  1067. });
  1068. beforeEach(() => {
  1069. contents = (webContents as any).create({
  1070. nodeIntegration: true,
  1071. contextIsolation: false
  1072. });
  1073. });
  1074. afterEach(() => {
  1075. (contents as any).destroy();
  1076. contents = null as any;
  1077. });
  1078. it('cannot access localStorage', async () => {
  1079. const response = emittedOnce(ipcMain, 'local-storage-response');
  1080. contents.loadURL(protocolName + '://host/localStorage');
  1081. const [, error] = await response;
  1082. expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.');
  1083. });
  1084. it('cannot access sessionStorage', async () => {
  1085. const response = emittedOnce(ipcMain, 'session-storage-response');
  1086. contents.loadURL(`${protocolName}://host/sessionStorage`);
  1087. const [, error] = await response;
  1088. expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.');
  1089. });
  1090. it('cannot access WebSQL database', async () => {
  1091. const response = emittedOnce(ipcMain, 'web-sql-response');
  1092. contents.loadURL(`${protocolName}://host/WebSQL`);
  1093. const [, error] = await response;
  1094. expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.');
  1095. });
  1096. it('cannot access indexedDB', async () => {
  1097. const response = emittedOnce(ipcMain, 'indexed-db-response');
  1098. contents.loadURL(`${protocolName}://host/indexedDB`);
  1099. const [, error] = await response;
  1100. expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.');
  1101. });
  1102. it('cannot access cookie', async () => {
  1103. const response = emittedOnce(ipcMain, 'cookie-response');
  1104. contents.loadURL(`${protocolName}://host/cookie`);
  1105. const [, error] = await response;
  1106. expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.');
  1107. });
  1108. });
  1109. describe('can be accessed', () => {
  1110. let server: http.Server;
  1111. let serverUrl: string;
  1112. let serverCrossSiteUrl: string;
  1113. before((done) => {
  1114. server = http.createServer((req, res) => {
  1115. const respond = () => {
  1116. if (req.url === '/redirect-cross-site') {
  1117. res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
  1118. res.statusCode = 302;
  1119. res.end();
  1120. } else if (req.url === '/redirected') {
  1121. res.end('<html><script>window.localStorage</script></html>');
  1122. } else {
  1123. res.end();
  1124. }
  1125. };
  1126. setTimeout(respond, 0);
  1127. });
  1128. server.listen(0, '127.0.0.1', () => {
  1129. serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  1130. serverCrossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`;
  1131. done();
  1132. });
  1133. });
  1134. after(() => {
  1135. server.close();
  1136. server = null as any;
  1137. });
  1138. afterEach(closeAllWindows);
  1139. const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
  1140. it(testTitle, async () => {
  1141. const w = new BrowserWindow({
  1142. show: false,
  1143. ...extraPreferences
  1144. });
  1145. let redirected = false;
  1146. w.webContents.on('crashed', () => {
  1147. expect.fail('renderer crashed / was killed');
  1148. });
  1149. w.webContents.on('did-redirect-navigation', (event, url) => {
  1150. expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
  1151. redirected = true;
  1152. });
  1153. await w.loadURL(`${serverUrl}/redirect-cross-site`);
  1154. expect(redirected).to.be.true('didnt redirect');
  1155. });
  1156. };
  1157. testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
  1158. testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
  1159. });
  1160. describe('enableWebSQL webpreference', () => {
  1161. const standardScheme = (global as any).standardScheme;
  1162. const origin = `${standardScheme}://fake-host`;
  1163. const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
  1164. const sqlPartition = 'web-sql-preference-test';
  1165. const sqlSession = session.fromPartition(sqlPartition);
  1166. const securityError = 'An attempt was made to break through the security policy of the user agent.';
  1167. let contents: WebContents, w: BrowserWindow;
  1168. before(() => {
  1169. sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
  1170. callback({ path: filePath });
  1171. });
  1172. });
  1173. after(() => {
  1174. sqlSession.protocol.unregisterProtocol(standardScheme);
  1175. });
  1176. afterEach(async () => {
  1177. if (contents) {
  1178. (contents as any).destroy();
  1179. contents = null as any;
  1180. }
  1181. await closeAllWindows();
  1182. (w as any) = null;
  1183. });
  1184. it('default value allows websql', async () => {
  1185. contents = (webContents as any).create({
  1186. session: sqlSession,
  1187. nodeIntegration: true,
  1188. contextIsolation: false
  1189. });
  1190. contents.loadURL(origin);
  1191. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1192. expect(error).to.be.null();
  1193. });
  1194. it('when set to false can disallow websql', async () => {
  1195. contents = (webContents as any).create({
  1196. session: sqlSession,
  1197. nodeIntegration: true,
  1198. enableWebSQL: false,
  1199. contextIsolation: false
  1200. });
  1201. contents.loadURL(origin);
  1202. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1203. expect(error).to.equal(securityError);
  1204. });
  1205. it('when set to false does not disable indexedDB', async () => {
  1206. contents = (webContents as any).create({
  1207. session: sqlSession,
  1208. nodeIntegration: true,
  1209. enableWebSQL: false,
  1210. contextIsolation: false
  1211. });
  1212. contents.loadURL(origin);
  1213. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1214. expect(error).to.equal(securityError);
  1215. const dbName = 'random';
  1216. const result = await contents.executeJavaScript(`
  1217. new Promise((resolve, reject) => {
  1218. try {
  1219. let req = window.indexedDB.open('${dbName}');
  1220. req.onsuccess = (event) => {
  1221. let db = req.result;
  1222. resolve(db.name);
  1223. }
  1224. req.onerror = (event) => { resolve(event.target.code); }
  1225. } catch (e) {
  1226. resolve(e.message);
  1227. }
  1228. });
  1229. `);
  1230. expect(result).to.equal(dbName);
  1231. });
  1232. it('child webContents can override when the embedder has allowed websql', async () => {
  1233. w = new BrowserWindow({
  1234. show: false,
  1235. webPreferences: {
  1236. nodeIntegration: true,
  1237. webviewTag: true,
  1238. session: sqlSession,
  1239. contextIsolation: false
  1240. }
  1241. });
  1242. w.webContents.loadURL(origin);
  1243. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1244. expect(error).to.be.null();
  1245. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1246. await w.webContents.executeJavaScript(`
  1247. new Promise((resolve, reject) => {
  1248. const webview = new WebView();
  1249. webview.setAttribute('src', '${origin}');
  1250. webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no');
  1251. webview.setAttribute('partition', '${sqlPartition}');
  1252. webview.setAttribute('nodeIntegration', 'on');
  1253. document.body.appendChild(webview);
  1254. webview.addEventListener('dom-ready', () => resolve());
  1255. });
  1256. `);
  1257. const [, childError] = await webviewResult;
  1258. expect(childError).to.equal(securityError);
  1259. });
  1260. it('child webContents cannot override when the embedder has disallowed websql', async () => {
  1261. w = new BrowserWindow({
  1262. show: false,
  1263. webPreferences: {
  1264. nodeIntegration: true,
  1265. enableWebSQL: false,
  1266. webviewTag: true,
  1267. session: sqlSession,
  1268. contextIsolation: false
  1269. }
  1270. });
  1271. w.webContents.loadURL('data:text/html,<html></html>');
  1272. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1273. await w.webContents.executeJavaScript(`
  1274. new Promise((resolve, reject) => {
  1275. const webview = new WebView();
  1276. webview.setAttribute('src', '${origin}');
  1277. webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
  1278. webview.setAttribute('partition', '${sqlPartition}');
  1279. webview.setAttribute('nodeIntegration', 'on');
  1280. document.body.appendChild(webview);
  1281. webview.addEventListener('dom-ready', () => resolve());
  1282. });
  1283. `);
  1284. const [, childError] = await webviewResult;
  1285. expect(childError).to.equal(securityError);
  1286. });
  1287. it('child webContents can use websql when the embedder has allowed websql', async () => {
  1288. w = new BrowserWindow({
  1289. show: false,
  1290. webPreferences: {
  1291. nodeIntegration: true,
  1292. webviewTag: true,
  1293. session: sqlSession,
  1294. contextIsolation: false
  1295. }
  1296. });
  1297. w.webContents.loadURL(origin);
  1298. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1299. expect(error).to.be.null();
  1300. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1301. await w.webContents.executeJavaScript(`
  1302. new Promise((resolve, reject) => {
  1303. const webview = new WebView();
  1304. webview.setAttribute('src', '${origin}');
  1305. webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
  1306. webview.setAttribute('partition', '${sqlPartition}');
  1307. webview.setAttribute('nodeIntegration', 'on');
  1308. document.body.appendChild(webview);
  1309. webview.addEventListener('dom-ready', () => resolve());
  1310. });
  1311. `);
  1312. const [, childError] = await webviewResult;
  1313. expect(childError).to.be.null();
  1314. });
  1315. });
  1316. });
  1317. ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
  1318. const pdfSource = url.format({
  1319. pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'),
  1320. protocol: 'file',
  1321. slashes: true
  1322. });
  1323. it('successfully loads a PDF file', async () => {
  1324. const w = new BrowserWindow({ show: false });
  1325. w.loadURL(pdfSource);
  1326. await emittedOnce(w.webContents, 'did-finish-load');
  1327. });
  1328. it('opens when loading a pdf resource as top level navigation', async () => {
  1329. const w = new BrowserWindow({ show: false });
  1330. w.loadURL(pdfSource);
  1331. const [, contents] = await emittedOnce(app, 'web-contents-created');
  1332. await emittedOnce(contents, 'did-navigate');
  1333. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1334. });
  1335. it('opens when loading a pdf resource in a iframe', async () => {
  1336. const w = new BrowserWindow({ show: false });
  1337. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
  1338. const [, contents] = await emittedOnce(app, 'web-contents-created');
  1339. await emittedOnce(contents, 'did-navigate');
  1340. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1341. });
  1342. });
  1343. describe('window.history', () => {
  1344. describe('window.history.pushState', () => {
  1345. it('should push state after calling history.pushState() from the same url', async () => {
  1346. const w = new BrowserWindow({ show: false });
  1347. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1348. // History should have current page by now.
  1349. expect((w.webContents as any).length()).to.equal(1);
  1350. const waitCommit = emittedOnce(w.webContents, 'navigation-entry-committed');
  1351. w.webContents.executeJavaScript('window.history.pushState({}, "")');
  1352. await waitCommit;
  1353. // Initial page + pushed state.
  1354. expect((w.webContents as any).length()).to.equal(2);
  1355. });
  1356. });
  1357. });
  1358. describe('chrome://media-internals', () => {
  1359. it('loads the page successfully', async () => {
  1360. const w = new BrowserWindow({ show: false });
  1361. w.loadURL('chrome://media-internals');
  1362. const pageExists = await w.webContents.executeJavaScript(
  1363. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1364. );
  1365. expect(pageExists).to.be.true();
  1366. });
  1367. });
  1368. describe('chrome://webrtc-internals', () => {
  1369. it('loads the page successfully', async () => {
  1370. const w = new BrowserWindow({ show: false });
  1371. w.loadURL('chrome://webrtc-internals');
  1372. const pageExists = await w.webContents.executeJavaScript(
  1373. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1374. );
  1375. expect(pageExists).to.be.true();
  1376. });
  1377. });
  1378. describe('document.hasFocus', () => {
  1379. it('has correct value when multiple windows are opened', async () => {
  1380. const w1 = new BrowserWindow({ show: true });
  1381. const w2 = new BrowserWindow({ show: true });
  1382. const w3 = new BrowserWindow({ show: false });
  1383. await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1384. await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1385. await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  1386. expect(webContents.getFocusedWebContents().id).to.equal(w2.webContents.id);
  1387. let focus = false;
  1388. focus = await w1.webContents.executeJavaScript(
  1389. 'document.hasFocus()'
  1390. );
  1391. expect(focus).to.be.false();
  1392. focus = await w2.webContents.executeJavaScript(
  1393. 'document.hasFocus()'
  1394. );
  1395. expect(focus).to.be.true();
  1396. focus = await w3.webContents.executeJavaScript(
  1397. 'document.hasFocus()'
  1398. );
  1399. expect(focus).to.be.false();
  1400. });
  1401. });
  1402. });
  1403. describe('font fallback', () => {
  1404. async function getRenderedFonts (html: string) {
  1405. const w = new BrowserWindow({ show: false });
  1406. try {
  1407. await w.loadURL(`data:text/html,${html}`);
  1408. w.webContents.debugger.attach();
  1409. const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
  1410. const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
  1411. await sendCommand('CSS.enable');
  1412. const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
  1413. return fonts;
  1414. } finally {
  1415. w.close();
  1416. }
  1417. }
  1418. it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
  1419. const html = '<body style="font-family: sans-serif">test</body>';
  1420. const fonts = await getRenderedFonts(html);
  1421. expect(fonts).to.be.an('array');
  1422. expect(fonts).to.have.length(1);
  1423. if (process.platform === 'win32') {
  1424. expect(fonts[0].familyName).to.equal('Arial');
  1425. } else if (process.platform === 'darwin') {
  1426. expect(fonts[0].familyName).to.equal('Helvetica');
  1427. } else if (process.platform === 'linux') {
  1428. expect(fonts[0].familyName).to.equal('DejaVu Sans');
  1429. } // I think this depends on the distro? We don't specify a default.
  1430. });
  1431. ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
  1432. const html = `
  1433. <html lang="ja-JP">
  1434. <head>
  1435. <meta charset="utf-8" />
  1436. </head>
  1437. <body style="font-family: sans-serif">test 智史</body>
  1438. </html>
  1439. `;
  1440. const fonts = await getRenderedFonts(html);
  1441. expect(fonts).to.be.an('array');
  1442. expect(fonts).to.have.length(1);
  1443. 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'); }
  1444. });
  1445. });
  1446. describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
  1447. const fullscreenChildHtml = promisify(fs.readFile)(
  1448. path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
  1449. );
  1450. let w: BrowserWindow, server: http.Server;
  1451. before(() => {
  1452. server = http.createServer(async (_req, res) => {
  1453. res.writeHead(200, { 'Content-Type': 'text/html' });
  1454. res.write(await fullscreenChildHtml);
  1455. res.end();
  1456. });
  1457. server.listen(8989, '127.0.0.1');
  1458. });
  1459. beforeEach(() => {
  1460. w = new BrowserWindow({
  1461. show: true,
  1462. fullscreen: true,
  1463. webPreferences: {
  1464. nodeIntegration: true,
  1465. nodeIntegrationInSubFrames: true,
  1466. contextIsolation: false
  1467. }
  1468. });
  1469. });
  1470. afterEach(async () => {
  1471. await closeAllWindows();
  1472. (w as any) = null;
  1473. server.close();
  1474. });
  1475. it('can fullscreen from out-of-process iframes (OOPIFs)', async () => {
  1476. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  1477. const html =
  1478. '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>';
  1479. w.loadURL(`data:text/html,${html}`);
  1480. await fullscreenChange;
  1481. const fullscreenWidth = await w.webContents.executeJavaScript(
  1482. "document.querySelector('iframe').offsetWidth"
  1483. );
  1484. expect(fullscreenWidth > 0).to.be.true();
  1485. await w.webContents.executeJavaScript(
  1486. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  1487. );
  1488. await delay(500);
  1489. const width = await w.webContents.executeJavaScript(
  1490. "document.querySelector('iframe').offsetWidth"
  1491. );
  1492. expect(width).to.equal(0);
  1493. });
  1494. it('can fullscreen from in-process iframes', async () => {
  1495. const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange');
  1496. w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
  1497. await fullscreenChange;
  1498. const fullscreenWidth = await w.webContents.executeJavaScript(
  1499. "document.querySelector('iframe').offsetWidth"
  1500. );
  1501. expect(fullscreenWidth > 0).to.true();
  1502. await w.webContents.executeJavaScript('document.exitFullscreen()');
  1503. const width = await w.webContents.executeJavaScript(
  1504. "document.querySelector('iframe').offsetWidth"
  1505. );
  1506. expect(width).to.equal(0);
  1507. });
  1508. });
  1509. describe('navigator.serial', () => {
  1510. let w: BrowserWindow;
  1511. before(async () => {
  1512. w = new BrowserWindow({
  1513. show: false
  1514. });
  1515. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1516. });
  1517. const getPorts: any = () => {
  1518. return w.webContents.executeJavaScript(`
  1519. navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
  1520. `, true);
  1521. };
  1522. after(closeAllWindows);
  1523. afterEach(() => {
  1524. session.defaultSession.setPermissionCheckHandler(null);
  1525. session.defaultSession.removeAllListeners('select-serial-port');
  1526. });
  1527. it('does not return a port if select-serial-port event is not defined', async () => {
  1528. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1529. const port = await getPorts();
  1530. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1531. });
  1532. it('does not return a port when permission denied', async () => {
  1533. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1534. callback(portList[0].portId);
  1535. });
  1536. session.defaultSession.setPermissionCheckHandler(() => false);
  1537. const port = await getPorts();
  1538. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1539. });
  1540. it('does not crash when select-serial-port is called with an invalid port', async () => {
  1541. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1542. callback('i-do-not-exist');
  1543. });
  1544. const port = await getPorts();
  1545. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1546. });
  1547. it('returns a port when select-serial-port event is defined', async () => {
  1548. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1549. callback(portList[0].portId);
  1550. });
  1551. const port = await getPorts();
  1552. expect(port).to.equal('[object SerialPort]');
  1553. });
  1554. });
  1555. describe('navigator.clipboard', () => {
  1556. let w: BrowserWindow;
  1557. before(async () => {
  1558. w = new BrowserWindow({
  1559. webPreferences: {
  1560. enableBlinkFeatures: 'Serial'
  1561. }
  1562. });
  1563. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1564. });
  1565. const readClipboard: any = () => {
  1566. return w.webContents.executeJavaScript(`
  1567. navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
  1568. `, true);
  1569. };
  1570. after(closeAllWindows);
  1571. afterEach(() => {
  1572. session.defaultSession.setPermissionRequestHandler(null);
  1573. });
  1574. it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
  1575. const clipboard = await readClipboard();
  1576. expect(clipboard).to.not.equal('Read permission denied.');
  1577. });
  1578. it('returns an error when permission denied', async () => {
  1579. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  1580. if (permission === 'clipboard-read') {
  1581. callback(false);
  1582. } else {
  1583. callback(true);
  1584. }
  1585. });
  1586. const clipboard = await readClipboard();
  1587. expect(clipboard).to.equal('Read permission denied.');
  1588. });
  1589. it('returns clipboard contents when permission is granted', async () => {
  1590. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  1591. if (permission === 'clipboard-read') {
  1592. callback(true);
  1593. } else {
  1594. callback(false);
  1595. }
  1596. });
  1597. const clipboard = await readClipboard();
  1598. expect(clipboard).to.not.equal('Read permission denied.');
  1599. });
  1600. });
  1601. ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
  1602. let w: BrowserWindow;
  1603. const expectedBadgeCount = 42;
  1604. const fireAppBadgeAction: any = (action: string, value: any) => {
  1605. return w.webContents.executeJavaScript(`
  1606. navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
  1607. };
  1608. // For some reason on macOS changing the badge count doesn't happen right away, so wait
  1609. // until it changes.
  1610. async function waitForBadgeCount (value: number) {
  1611. let badgeCount = app.getBadgeCount();
  1612. while (badgeCount !== value) {
  1613. await new Promise(resolve => setTimeout(resolve, 10));
  1614. badgeCount = app.getBadgeCount();
  1615. }
  1616. return badgeCount;
  1617. }
  1618. describe('in the renderer', () => {
  1619. before(async () => {
  1620. w = new BrowserWindow({
  1621. show: false
  1622. });
  1623. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1624. });
  1625. after(() => {
  1626. app.badgeCount = 0;
  1627. closeAllWindows();
  1628. });
  1629. it('setAppBadge can set a numerical value', async () => {
  1630. const result = await fireAppBadgeAction('set', expectedBadgeCount);
  1631. expect(result).to.equal('success');
  1632. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1633. });
  1634. it('setAppBadge can set an empty(dot) value', async () => {
  1635. const result = await fireAppBadgeAction('set');
  1636. expect(result).to.equal('success');
  1637. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  1638. });
  1639. it('clearAppBadge can clear a value', async () => {
  1640. let result = await fireAppBadgeAction('set', expectedBadgeCount);
  1641. expect(result).to.equal('success');
  1642. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1643. result = await fireAppBadgeAction('clear');
  1644. expect(result).to.equal('success');
  1645. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  1646. });
  1647. });
  1648. describe('in a service worker', () => {
  1649. beforeEach(async () => {
  1650. w = new BrowserWindow({
  1651. show: false,
  1652. webPreferences: {
  1653. nodeIntegration: true,
  1654. partition: 'sw-file-scheme-spec',
  1655. contextIsolation: false
  1656. }
  1657. });
  1658. });
  1659. afterEach(() => {
  1660. app.badgeCount = 0;
  1661. closeAllWindows();
  1662. });
  1663. it('setAppBadge can be called in a ServiceWorker', (done) => {
  1664. w.webContents.on('ipc-message', (event, channel, message) => {
  1665. if (channel === 'reload') {
  1666. w.webContents.reload();
  1667. } else if (channel === 'error') {
  1668. done(message);
  1669. } else if (channel === 'response') {
  1670. expect(message).to.equal('SUCCESS setting app badge');
  1671. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1672. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  1673. storages: ['serviceworkers']
  1674. }).then(() => done());
  1675. }
  1676. });
  1677. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  1678. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
  1679. });
  1680. it('clearAppBadge can be called in a ServiceWorker', (done) => {
  1681. w.webContents.on('ipc-message', (event, channel, message) => {
  1682. if (channel === 'reload') {
  1683. w.webContents.reload();
  1684. } else if (channel === 'setAppBadge') {
  1685. expect(message).to.equal('SUCCESS setting app badge');
  1686. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1687. } else if (channel === 'error') {
  1688. done(message);
  1689. } else if (channel === 'response') {
  1690. expect(message).to.equal('SUCCESS clearing app badge');
  1691. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1692. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  1693. storages: ['serviceworkers']
  1694. }).then(() => done());
  1695. }
  1696. });
  1697. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  1698. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
  1699. });
  1700. });
  1701. });
  1702. describe('navigator.bluetooth', () => {
  1703. let w: BrowserWindow;
  1704. before(async () => {
  1705. w = new BrowserWindow({
  1706. show: false,
  1707. webPreferences: {
  1708. enableBlinkFeatures: 'WebBluetooth'
  1709. }
  1710. });
  1711. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1712. });
  1713. after(closeAllWindows);
  1714. it('can request bluetooth devices', async () => {
  1715. const bluetooth = await w.webContents.executeJavaScript(`
  1716. navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
  1717. expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
  1718. });
  1719. });
  1720. describe('navigator.hid', () => {
  1721. let w: BrowserWindow;
  1722. let server: http.Server;
  1723. let serverUrl: string;
  1724. before(async () => {
  1725. w = new BrowserWindow({
  1726. show: false
  1727. });
  1728. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1729. server = http.createServer((req, res) => {
  1730. res.setHeader('Content-Type', 'text/html');
  1731. res.end('<body>');
  1732. });
  1733. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1734. serverUrl = `http://localhost:${(server.address() as any).port}`;
  1735. });
  1736. const getDevices: any = () => {
  1737. return w.webContents.executeJavaScript(`
  1738. navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
  1739. `, true);
  1740. };
  1741. after(() => {
  1742. server.close();
  1743. closeAllWindows();
  1744. });
  1745. afterEach(() => {
  1746. session.defaultSession.setPermissionCheckHandler(null);
  1747. session.defaultSession.setDevicePermissionHandler(null);
  1748. session.defaultSession.removeAllListeners('select-hid-device');
  1749. });
  1750. it('does not return a device if select-hid-device event is not defined', async () => {
  1751. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1752. const device = await getDevices();
  1753. expect(device).to.equal('');
  1754. });
  1755. it('does not return a device when permission denied', async () => {
  1756. let selectFired = false;
  1757. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  1758. selectFired = true;
  1759. callback();
  1760. });
  1761. session.defaultSession.setPermissionCheckHandler(() => false);
  1762. const device = await getDevices();
  1763. expect(selectFired).to.be.false();
  1764. expect(device).to.equal('');
  1765. });
  1766. it('returns a device when select-hid-device event is defined', async () => {
  1767. let haveDevices = false;
  1768. let selectFired = false;
  1769. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  1770. expect(details.frame).to.have.ownProperty('frameTreeNodeId').that.is.a('number');
  1771. selectFired = true;
  1772. if (details.deviceList.length > 0) {
  1773. haveDevices = true;
  1774. callback(details.deviceList[0].deviceId);
  1775. } else {
  1776. callback();
  1777. }
  1778. });
  1779. const device = await getDevices();
  1780. expect(selectFired).to.be.true();
  1781. if (haveDevices) {
  1782. expect(device).to.contain('[object HIDDevice]');
  1783. } else {
  1784. expect(device).to.equal('');
  1785. }
  1786. if (process.arch === 'arm64' || process.arch === 'arm') {
  1787. // arm CI returns HID devices - this block may need to change if CI hardware changes.
  1788. expect(haveDevices).to.be.true();
  1789. // Verify that navigation will clear device permissions
  1790. const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
  1791. expect(grantedDevices).to.not.be.empty();
  1792. w.loadURL(serverUrl);
  1793. const [,,,,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-navigate');
  1794. const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
  1795. expect(frame).to.not.be.empty();
  1796. if (frame) {
  1797. const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
  1798. expect(grantedDevicesOnNewPage).to.be.empty();
  1799. }
  1800. }
  1801. });
  1802. it('returns a device when DevicePermissionHandler is defined', async () => {
  1803. let haveDevices = false;
  1804. let selectFired = false;
  1805. let gotDevicePerms = false;
  1806. w.webContents.session.on('select-hid-device', (event, details, callback) => {
  1807. selectFired = true;
  1808. if (details.deviceList.length > 0) {
  1809. const foundDevice = details.deviceList.find((device) => {
  1810. if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
  1811. haveDevices = true;
  1812. return true;
  1813. }
  1814. });
  1815. if (foundDevice) {
  1816. callback(foundDevice.deviceId);
  1817. return;
  1818. }
  1819. }
  1820. callback();
  1821. });
  1822. session.defaultSession.setDevicePermissionHandler(() => {
  1823. gotDevicePerms = true;
  1824. return true;
  1825. });
  1826. await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
  1827. const device = await getDevices();
  1828. expect(selectFired).to.be.true();
  1829. if (haveDevices) {
  1830. expect(device).to.contain('[object HIDDevice]');
  1831. expect(gotDevicePerms).to.be.true();
  1832. } else {
  1833. expect(device).to.equal('');
  1834. }
  1835. });
  1836. });