chromium-spec.ts 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923
  1. import { expect } from 'chai';
  2. import { BrowserWindow, WebContents, 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-eval" csp', async () => {
  319. const r = await loadWasm("'wasm-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. ifdescribe(process.platform === 'linux')('subprocesses', () => {
  332. let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
  333. afterEach(() => {
  334. if (appProcess && !appProcess.killed) {
  335. appProcess.kill();
  336. appProcess = undefined;
  337. }
  338. });
  339. it('does not propagate GDK_BACKEND', async () => {
  340. const appPath = path.join(fixturesPath, 'api', 'gdk-backend-check');
  341. appProcess = ChildProcess.spawn(process.execPath, [appPath], {
  342. env: {
  343. GDK_BACKEND: ''
  344. }
  345. });
  346. let output = '';
  347. appProcess.stdout.on('data', (data) => { output += data; });
  348. let stderr = '';
  349. appProcess.stderr.on('data', (data) => { stderr += data; });
  350. const [code, signal] = await emittedOnce(appProcess, 'exit');
  351. if (code !== 0) {
  352. throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
  353. }
  354. output = output.replace(/(\r\n|\n|\r)/gm, '');
  355. const backend = String(process.env.GDK_BACKEND);
  356. expect(output).to.not.equal(backend);
  357. expect(output).to.be.empty();
  358. });
  359. it('successfully honors GDK_BACKEND set in the subproc', async () => {
  360. const appPath = path.join(fixturesPath, 'api', 'gdk-backend-check');
  361. appProcess = ChildProcess.spawn(process.execPath, [appPath], {
  362. env: {
  363. GDK_BACKEND: 'wayland'
  364. }
  365. });
  366. let output = '';
  367. appProcess.stdout.on('data', (data) => { output += data; });
  368. let stderr = '';
  369. appProcess.stderr.on('data', (data) => { stderr += data; });
  370. const [code, signal] = await emittedOnce(appProcess, 'exit');
  371. if (code !== 0) {
  372. throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
  373. }
  374. output = output.replace(/(\r\n|\n|\r)/gm, '');
  375. const backend = String(process.env.GDK_BACKEND);
  376. expect(output).to.not.equal(backend);
  377. expect(output).to.equal('wayland');
  378. });
  379. });
  380. describe('command line switches', () => {
  381. let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
  382. afterEach(() => {
  383. if (appProcess && !appProcess.killed) {
  384. appProcess.kill();
  385. appProcess = undefined;
  386. }
  387. });
  388. describe('--lang switch', () => {
  389. const currentLocale = app.getLocale();
  390. const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
  391. const appPath = path.join(fixturesPath, 'api', 'locale-check');
  392. const args = [appPath, `--set-lang=${locale}`];
  393. if (printEnv) {
  394. args.push('--print-env');
  395. }
  396. appProcess = ChildProcess.spawn(process.execPath, args);
  397. let output = '';
  398. appProcess.stdout.on('data', (data) => { output += data; });
  399. let stderr = '';
  400. appProcess.stderr.on('data', (data) => { stderr += data; });
  401. const [code, signal] = await emittedOnce(appProcess, 'exit');
  402. if (code !== 0) {
  403. throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
  404. }
  405. output = output.replace(/(\r\n|\n|\r)/gm, '');
  406. expect(output).to.equal(result);
  407. };
  408. it('should set the locale', async () => testLocale('fr', 'fr'));
  409. it('should not set an invalid locale', async () => testLocale('asdfkl', currentLocale));
  410. const lcAll = String(process.env.LC_ALL);
  411. ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
  412. // The LC_ALL env should not be set to DOM locale string.
  413. expect(lcAll).to.not.equal(app.getLocale());
  414. });
  415. ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
  416. ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
  417. ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
  418. });
  419. describe('--remote-debugging-pipe switch', () => {
  420. it('should expose CDP via pipe', async () => {
  421. const electronPath = process.execPath;
  422. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
  423. stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
  424. }) as ChildProcess.ChildProcessWithoutNullStreams;
  425. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  426. const pipe = new PipeTransport(stdio[3], stdio[4]);
  427. const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
  428. pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
  429. const message = (await versionPromise) as any;
  430. expect(message.id).to.equal(1);
  431. expect(message.result.product).to.contain('Chrome');
  432. expect(message.result.userAgent).to.contain('Electron');
  433. });
  434. it('should override --remote-debugging-port switch', async () => {
  435. const electronPath = process.execPath;
  436. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], {
  437. stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe']
  438. }) as ChildProcess.ChildProcessWithoutNullStreams;
  439. let stderr = '';
  440. appProcess.stderr.on('data', (data: string) => { stderr += data; });
  441. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  442. const pipe = new PipeTransport(stdio[3], stdio[4]);
  443. const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
  444. pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
  445. const message = (await versionPromise) as any;
  446. expect(message.id).to.equal(1);
  447. expect(stderr).to.not.include('DevTools listening on');
  448. });
  449. it('should shut down Electron upon Browser.close CDP command', async () => {
  450. const electronPath = process.execPath;
  451. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
  452. stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
  453. }) as ChildProcess.ChildProcessWithoutNullStreams;
  454. const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
  455. const pipe = new PipeTransport(stdio[3], stdio[4]);
  456. pipe.send({ id: 1, method: 'Browser.close', params: {} });
  457. await new Promise(resolve => { appProcess!.on('exit', resolve); });
  458. });
  459. });
  460. describe('--remote-debugging-port switch', () => {
  461. it('should display the discovery page', (done) => {
  462. const electronPath = process.execPath;
  463. let output = '';
  464. appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']);
  465. appProcess.stdout.on('data', (data) => {
  466. console.log(data);
  467. });
  468. appProcess.stderr.on('data', (data) => {
  469. console.log(data);
  470. output += data;
  471. const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
  472. if (m) {
  473. appProcess!.stderr.removeAllListeners('data');
  474. const port = m[1];
  475. http.get(`http://127.0.0.1:${port}`, (res) => {
  476. try {
  477. expect(res.statusCode).to.eql(200);
  478. expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
  479. done();
  480. } catch (e) {
  481. done(e);
  482. } finally {
  483. res.destroy();
  484. }
  485. });
  486. }
  487. });
  488. });
  489. });
  490. });
  491. describe('chromium features', () => {
  492. afterEach(closeAllWindows);
  493. describe('accessing key names also used as Node.js module names', () => {
  494. it('does not crash', (done) => {
  495. const w = new BrowserWindow({ show: false });
  496. w.webContents.once('did-finish-load', () => { done(); });
  497. w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
  498. w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
  499. });
  500. });
  501. describe('loading jquery', () => {
  502. it('does not crash', (done) => {
  503. const w = new BrowserWindow({ show: false });
  504. w.webContents.once('did-finish-load', () => { done(); });
  505. w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
  506. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
  507. });
  508. });
  509. describe('navigator.languages', () => {
  510. it('should return the system locale only', async () => {
  511. const appLocale = app.getLocale();
  512. const w = new BrowserWindow({ show: false });
  513. await w.loadURL('about:blank');
  514. const languages = await w.webContents.executeJavaScript('navigator.languages');
  515. expect(languages.length).to.be.greaterThan(0);
  516. expect(languages).to.contain(appLocale);
  517. });
  518. });
  519. describe('navigator.serviceWorker', () => {
  520. it('should register for file scheme', (done) => {
  521. const w = new BrowserWindow({
  522. show: false,
  523. webPreferences: {
  524. nodeIntegration: true,
  525. partition: 'sw-file-scheme-spec',
  526. contextIsolation: false
  527. }
  528. });
  529. w.webContents.on('ipc-message', (event, channel, message) => {
  530. if (channel === 'reload') {
  531. w.webContents.reload();
  532. } else if (channel === 'error') {
  533. done(message);
  534. } else if (channel === 'response') {
  535. expect(message).to.equal('Hello from serviceWorker!');
  536. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  537. storages: ['serviceworkers']
  538. }).then(() => done());
  539. }
  540. });
  541. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  542. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  543. });
  544. it('should register for intercepted file scheme', (done) => {
  545. const customSession = session.fromPartition('intercept-file');
  546. customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
  547. let file = url.parse(request.url).pathname!;
  548. if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
  549. const content = fs.readFileSync(path.normalize(file));
  550. const ext = path.extname(file);
  551. let type = 'text/html';
  552. if (ext === '.js') type = 'application/javascript';
  553. callback({ data: content, mimeType: type } as any);
  554. });
  555. const w = new BrowserWindow({
  556. show: false,
  557. webPreferences: {
  558. nodeIntegration: true,
  559. session: customSession,
  560. contextIsolation: false
  561. }
  562. });
  563. w.webContents.on('ipc-message', (event, channel, message) => {
  564. if (channel === 'reload') {
  565. w.webContents.reload();
  566. } else if (channel === 'error') {
  567. done(`unexpected error : ${message}`);
  568. } else if (channel === 'response') {
  569. expect(message).to.equal('Hello from serviceWorker!');
  570. customSession.clearStorageData({
  571. storages: ['serviceworkers']
  572. }).then(() => {
  573. customSession.protocol.uninterceptProtocol('file');
  574. done();
  575. });
  576. }
  577. });
  578. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  579. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  580. });
  581. it('should register for custom scheme', (done) => {
  582. const customSession = session.fromPartition('custom-scheme');
  583. const { serviceWorkerScheme } = global as any;
  584. customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => {
  585. let file = url.parse(request.url).pathname!;
  586. if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
  587. callback({ path: path.normalize(file) } as any);
  588. });
  589. const w = new BrowserWindow({
  590. show: false,
  591. webPreferences: {
  592. nodeIntegration: true,
  593. session: customSession,
  594. contextIsolation: false
  595. }
  596. });
  597. w.webContents.on('ipc-message', (event, channel, message) => {
  598. if (channel === 'reload') {
  599. w.webContents.reload();
  600. } else if (channel === 'error') {
  601. done(`unexpected error : ${message}`);
  602. } else if (channel === 'response') {
  603. expect(message).to.equal('Hello from serviceWorker!');
  604. customSession.clearStorageData({
  605. storages: ['serviceworkers']
  606. }).then(() => {
  607. customSession.protocol.uninterceptProtocol(serviceWorkerScheme);
  608. done();
  609. });
  610. }
  611. });
  612. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  613. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html'));
  614. });
  615. it('should not crash when nodeIntegration is enabled', (done) => {
  616. const w = new BrowserWindow({
  617. show: false,
  618. webPreferences: {
  619. nodeIntegration: true,
  620. nodeIntegrationInWorker: true,
  621. partition: 'sw-file-scheme-worker-spec',
  622. contextIsolation: false
  623. }
  624. });
  625. w.webContents.on('ipc-message', (event, channel, message) => {
  626. if (channel === 'reload') {
  627. w.webContents.reload();
  628. } else if (channel === 'error') {
  629. done(`unexpected error : ${message}`);
  630. } else if (channel === 'response') {
  631. expect(message).to.equal('Hello from serviceWorker!');
  632. session.fromPartition('sw-file-scheme-worker-spec').clearStorageData({
  633. storages: ['serviceworkers']
  634. }).then(() => done());
  635. }
  636. });
  637. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  638. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  639. });
  640. });
  641. describe('navigator.geolocation', () => {
  642. before(function () {
  643. if (!features.isFakeLocationProviderEnabled()) {
  644. return this.skip();
  645. }
  646. });
  647. it('returns error when permission is denied', async () => {
  648. const w = new BrowserWindow({
  649. show: false,
  650. webPreferences: {
  651. nodeIntegration: true,
  652. partition: 'geolocation-spec',
  653. contextIsolation: false
  654. }
  655. });
  656. const message = emittedOnce(w.webContents, 'ipc-message');
  657. w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
  658. if (permission === 'geolocation') {
  659. callback(false);
  660. } else {
  661. callback(true);
  662. }
  663. });
  664. w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
  665. const [, channel] = await message;
  666. expect(channel).to.equal('success', 'unexpected response from geolocation api');
  667. });
  668. });
  669. describe('form submit', () => {
  670. let server: http.Server;
  671. let serverUrl: string;
  672. before(async () => {
  673. server = http.createServer((req, res) => {
  674. let body = '';
  675. req.on('data', (chunk) => {
  676. body += chunk;
  677. });
  678. res.setHeader('Content-Type', 'application/json');
  679. req.on('end', () => {
  680. res.end(`body:${body}`);
  681. });
  682. });
  683. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  684. serverUrl = `http://localhost:${(server.address() as any).port}`;
  685. });
  686. after(async () => {
  687. server.close();
  688. await closeAllWindows();
  689. });
  690. [true, false].forEach((isSandboxEnabled) =>
  691. describe(`sandbox=${isSandboxEnabled}`, () => {
  692. it('posts data in the same window', async () => {
  693. const w = new BrowserWindow({
  694. show: false,
  695. webPreferences: {
  696. sandbox: isSandboxEnabled
  697. }
  698. });
  699. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  700. const loadPromise = emittedOnce(w.webContents, 'did-finish-load');
  701. w.webContents.executeJavaScript(`
  702. const form = document.querySelector('form')
  703. form.action = '${serverUrl}';
  704. form.submit();
  705. `);
  706. await loadPromise;
  707. const res = await w.webContents.executeJavaScript('document.body.innerText');
  708. expect(res).to.equal('body:greeting=hello');
  709. });
  710. it('posts data to a new window with target=_blank', async () => {
  711. const w = new BrowserWindow({
  712. show: false,
  713. webPreferences: {
  714. sandbox: isSandboxEnabled
  715. }
  716. });
  717. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  718. const windowCreatedPromise = emittedOnce(app, 'browser-window-created');
  719. w.webContents.executeJavaScript(`
  720. const form = document.querySelector('form')
  721. form.action = '${serverUrl}';
  722. form.target = '_blank';
  723. form.submit();
  724. `);
  725. const [, newWin] = await windowCreatedPromise;
  726. const res = await newWin.webContents.executeJavaScript('document.body.innerText');
  727. expect(res).to.equal('body:greeting=hello');
  728. });
  729. })
  730. );
  731. });
  732. describe('window.open', () => {
  733. for (const show of [true, false]) {
  734. it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => {
  735. const w = new BrowserWindow({ show });
  736. // toggle visibility
  737. if (show) {
  738. w.hide();
  739. } else {
  740. w.show();
  741. }
  742. defer(() => { w.close(); });
  743. const newWindow = emittedOnce(w.webContents, 'new-window');
  744. w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
  745. const [,,,, options] = await newWindow;
  746. expect(options.show).to.equal(true);
  747. });
  748. }
  749. it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
  750. // NB. webSecurity is disabled because native window.open() is not
  751. // allowed to load devtools:// URLs.
  752. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } });
  753. w.loadURL('about:blank');
  754. w.webContents.executeJavaScript(`
  755. { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null }
  756. `);
  757. const [, contents] = await emittedOnce(app, 'web-contents-created');
  758. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  759. expect(typeofProcessGlobal).to.equal('undefined');
  760. });
  761. it('disables JavaScript when it is disabled on the parent window', async () => {
  762. const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } });
  763. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  764. const windowUrl = require('url').format({
  765. pathname: `${fixturesPath}/pages/window-no-javascript.html`,
  766. protocol: 'file',
  767. slashes: true
  768. });
  769. w.webContents.executeJavaScript(`
  770. { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null }
  771. `);
  772. const [, contents] = await emittedOnce(app, 'web-contents-created');
  773. await emittedOnce(contents, 'did-finish-load');
  774. // Click link on page
  775. contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
  776. contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
  777. const [, window] = await emittedOnce(app, 'browser-window-created');
  778. const preferences = window.webContents.getLastWebPreferences();
  779. expect(preferences.javascript).to.be.false();
  780. });
  781. it('defines a window.location getter', async () => {
  782. let targetURL: string;
  783. if (process.platform === 'win32') {
  784. targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
  785. } else {
  786. targetURL = `file://${fixturesPath}/pages/base-page.html`;
  787. }
  788. const w = new BrowserWindow({ show: false });
  789. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  790. w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
  791. const [, window] = await emittedOnce(app, 'browser-window-created');
  792. await emittedOnce(window.webContents, 'did-finish-load');
  793. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
  794. });
  795. it('defines a window.location setter', async () => {
  796. const w = new BrowserWindow({ show: false });
  797. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  798. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  799. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  800. await emittedOnce(webContents, 'did-finish-load');
  801. // When it loads, redirect
  802. w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  803. await emittedOnce(webContents, 'did-finish-load');
  804. });
  805. it('defines a window.location.href setter', async () => {
  806. const w = new BrowserWindow({ show: false });
  807. w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
  808. w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
  809. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  810. await emittedOnce(webContents, 'did-finish-load');
  811. // When it loads, redirect
  812. w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  813. await emittedOnce(webContents, 'did-finish-load');
  814. });
  815. it('open a blank page when no URL is specified', async () => {
  816. const w = new BrowserWindow({ show: false });
  817. w.loadURL('about:blank');
  818. w.webContents.executeJavaScript('{ b = window.open(); null }');
  819. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  820. await emittedOnce(webContents, 'did-finish-load');
  821. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  822. });
  823. it('open a blank page when an empty URL is specified', async () => {
  824. const w = new BrowserWindow({ show: false });
  825. w.loadURL('about:blank');
  826. w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
  827. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  828. await emittedOnce(webContents, 'did-finish-load');
  829. expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
  830. });
  831. it('does not throw an exception when the frameName is a built-in object property', async () => {
  832. const w = new BrowserWindow({ show: false });
  833. w.loadURL('about:blank');
  834. w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
  835. const [, , frameName] = await emittedOnce(w.webContents, 'new-window');
  836. expect(frameName).to.equal('__proto__');
  837. });
  838. it('denies custom open when nativeWindowOpen: true', async () => {
  839. const w = new BrowserWindow({
  840. show: false,
  841. webPreferences: {
  842. contextIsolation: false,
  843. nodeIntegration: true,
  844. nativeWindowOpen: true
  845. }
  846. });
  847. w.loadURL('about:blank');
  848. const previousListeners = process.listeners('uncaughtException');
  849. process.removeAllListeners('uncaughtException');
  850. try {
  851. const uncaughtException = new Promise<Error>(resolve => {
  852. process.once('uncaughtException', resolve);
  853. });
  854. expect(await w.webContents.executeJavaScript(`(${function () {
  855. const { ipc } = process._linkedBinding('electron_renderer_ipc');
  856. return ipc.sendSync(true, 'GUEST_WINDOW_MANAGER_WINDOW_OPEN', ['', '', '']);
  857. }})()`)).to.be.null();
  858. const exception = await uncaughtException;
  859. expect(exception.message).to.match(/denied: expected native window\.open/);
  860. } finally {
  861. previousListeners.forEach(l => process.on('uncaughtException', l));
  862. }
  863. });
  864. });
  865. describe('window.opener', () => {
  866. it('is null for main window', async () => {
  867. const w = new BrowserWindow({
  868. show: false,
  869. webPreferences: {
  870. nodeIntegration: true,
  871. contextIsolation: false
  872. }
  873. });
  874. w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
  875. const [, channel, opener] = await emittedOnce(w.webContents, 'ipc-message');
  876. expect(channel).to.equal('opener');
  877. expect(opener).to.equal(null);
  878. });
  879. });
  880. describe('navigator.mediaDevices', () => {
  881. afterEach(closeAllWindows);
  882. afterEach(() => {
  883. session.defaultSession.setPermissionCheckHandler(null);
  884. });
  885. it('can return labels of enumerated devices', async () => {
  886. const w = new BrowserWindow({ show: false });
  887. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  888. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  889. expect(labels.some((l: any) => l)).to.be.true();
  890. });
  891. it('does not return labels of enumerated devices when permission denied', async () => {
  892. session.defaultSession.setPermissionCheckHandler(() => false);
  893. const w = new BrowserWindow({ show: false });
  894. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  895. const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
  896. expect(labels.some((l: any) => l)).to.be.false();
  897. });
  898. it('returns the same device ids across reloads', async () => {
  899. const ses = session.fromPartition('persist:media-device-id');
  900. const w = new BrowserWindow({
  901. show: false,
  902. webPreferences: {
  903. nodeIntegration: true,
  904. session: ses,
  905. contextIsolation: false
  906. }
  907. });
  908. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  909. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  910. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  911. expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
  912. });
  913. it('can return new device id when cookie storage is cleared', async () => {
  914. const ses = session.fromPartition('persist:media-device-id');
  915. const w = new BrowserWindow({
  916. show: false,
  917. webPreferences: {
  918. nodeIntegration: true,
  919. session: ses,
  920. contextIsolation: false
  921. }
  922. });
  923. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  924. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  925. await ses.clearStorageData({ storages: ['cookies'] });
  926. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  927. expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
  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, nativeWindowOpen: 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. webPreferences: {
  1515. enableBlinkFeatures: 'Serial'
  1516. }
  1517. });
  1518. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1519. });
  1520. const getPorts: any = () => {
  1521. return w.webContents.executeJavaScript(`
  1522. navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
  1523. `, true);
  1524. };
  1525. after(closeAllWindows);
  1526. afterEach(() => {
  1527. session.defaultSession.setPermissionCheckHandler(null);
  1528. session.defaultSession.removeAllListeners('select-serial-port');
  1529. });
  1530. it('does not return a port if select-serial-port event is not defined', async () => {
  1531. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1532. const port = await getPorts();
  1533. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1534. });
  1535. it('does not return a port when permission denied', async () => {
  1536. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1537. callback(portList[0].portId);
  1538. });
  1539. session.defaultSession.setPermissionCheckHandler(() => false);
  1540. const port = await getPorts();
  1541. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1542. });
  1543. it('does not crash when select-serial-port is called with an invalid port', async () => {
  1544. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1545. callback('i-do-not-exist');
  1546. });
  1547. const port = await getPorts();
  1548. expect(port).to.equal('NotFoundError: No port selected by the user.');
  1549. });
  1550. it('returns a port when select-serial-port event is defined', async () => {
  1551. w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
  1552. callback(portList[0].portId);
  1553. });
  1554. const port = await getPorts();
  1555. expect(port).to.equal('[object SerialPort]');
  1556. });
  1557. });
  1558. describe('navigator.clipboard', () => {
  1559. let w: BrowserWindow;
  1560. before(async () => {
  1561. w = new BrowserWindow({
  1562. webPreferences: {
  1563. enableBlinkFeatures: 'Serial'
  1564. }
  1565. });
  1566. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1567. });
  1568. const readClipboard: any = () => {
  1569. return w.webContents.executeJavaScript(`
  1570. navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
  1571. `, true);
  1572. };
  1573. after(closeAllWindows);
  1574. afterEach(() => {
  1575. session.defaultSession.setPermissionRequestHandler(null);
  1576. });
  1577. it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
  1578. const clipboard = await readClipboard();
  1579. expect(clipboard).to.not.equal('Read permission denied.');
  1580. });
  1581. it('returns an error when permission denied', async () => {
  1582. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  1583. if (permission === 'clipboard-read') {
  1584. callback(false);
  1585. } else {
  1586. callback(true);
  1587. }
  1588. });
  1589. const clipboard = await readClipboard();
  1590. expect(clipboard).to.equal('Read permission denied.');
  1591. });
  1592. it('returns clipboard contents when permission is granted', async () => {
  1593. session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
  1594. if (permission === 'clipboard-read') {
  1595. callback(true);
  1596. } else {
  1597. callback(false);
  1598. }
  1599. });
  1600. const clipboard = await readClipboard();
  1601. expect(clipboard).to.not.equal('Read permission denied.');
  1602. });
  1603. });
  1604. ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
  1605. let w: BrowserWindow;
  1606. const expectedBadgeCount = 42;
  1607. const fireAppBadgeAction: any = (action: string, value: any) => {
  1608. return w.webContents.executeJavaScript(`
  1609. navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
  1610. };
  1611. // For some reason on macOS changing the badge count doesn't happen right away, so wait
  1612. // until it changes.
  1613. async function waitForBadgeCount (value: number) {
  1614. let badgeCount = app.getBadgeCount();
  1615. while (badgeCount !== value) {
  1616. await new Promise(resolve => setTimeout(resolve, 10));
  1617. badgeCount = app.getBadgeCount();
  1618. }
  1619. return badgeCount;
  1620. }
  1621. describe('in the renderer', () => {
  1622. before(async () => {
  1623. w = new BrowserWindow({
  1624. show: false
  1625. });
  1626. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1627. });
  1628. after(() => {
  1629. app.badgeCount = 0;
  1630. closeAllWindows();
  1631. });
  1632. it('setAppBadge can set a numerical value', async () => {
  1633. const result = await fireAppBadgeAction('set', expectedBadgeCount);
  1634. expect(result).to.equal('success');
  1635. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1636. });
  1637. it('setAppBadge can set an empty(dot) value', async () => {
  1638. const result = await fireAppBadgeAction('set');
  1639. expect(result).to.equal('success');
  1640. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  1641. });
  1642. it('clearAppBadge can clear a value', async () => {
  1643. let result = await fireAppBadgeAction('set', expectedBadgeCount);
  1644. expect(result).to.equal('success');
  1645. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1646. result = await fireAppBadgeAction('clear');
  1647. expect(result).to.equal('success');
  1648. expect(waitForBadgeCount(0)).to.eventually.equal(0);
  1649. });
  1650. });
  1651. describe('in a service worker', () => {
  1652. beforeEach(async () => {
  1653. w = new BrowserWindow({
  1654. show: false,
  1655. webPreferences: {
  1656. nodeIntegration: true,
  1657. partition: 'sw-file-scheme-spec',
  1658. contextIsolation: false
  1659. }
  1660. });
  1661. });
  1662. afterEach(() => {
  1663. app.badgeCount = 0;
  1664. closeAllWindows();
  1665. });
  1666. it('setAppBadge can be called in a ServiceWorker', (done) => {
  1667. w.webContents.on('ipc-message', (event, channel, message) => {
  1668. if (channel === 'reload') {
  1669. w.webContents.reload();
  1670. } else if (channel === 'error') {
  1671. done(message);
  1672. } else if (channel === 'response') {
  1673. expect(message).to.equal('SUCCESS setting app badge');
  1674. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1675. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  1676. storages: ['serviceworkers']
  1677. }).then(() => done());
  1678. }
  1679. });
  1680. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  1681. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
  1682. });
  1683. it('clearAppBadge can be called in a ServiceWorker', (done) => {
  1684. w.webContents.on('ipc-message', (event, channel, message) => {
  1685. if (channel === 'reload') {
  1686. w.webContents.reload();
  1687. } else if (channel === 'setAppBadge') {
  1688. expect(message).to.equal('SUCCESS setting app badge');
  1689. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1690. } else if (channel === 'error') {
  1691. done(message);
  1692. } else if (channel === 'response') {
  1693. expect(message).to.equal('SUCCESS clearing app badge');
  1694. expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
  1695. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  1696. storages: ['serviceworkers']
  1697. }).then(() => done());
  1698. }
  1699. });
  1700. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  1701. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
  1702. });
  1703. });
  1704. });
  1705. describe('navigator.bluetooth', () => {
  1706. let w: BrowserWindow;
  1707. before(async () => {
  1708. w = new BrowserWindow({
  1709. show: false,
  1710. webPreferences: {
  1711. enableBlinkFeatures: 'WebBluetooth'
  1712. }
  1713. });
  1714. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1715. });
  1716. after(closeAllWindows);
  1717. it('can request bluetooth devices', async () => {
  1718. const bluetooth = await w.webContents.executeJavaScript(`
  1719. navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
  1720. expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
  1721. });
  1722. });