chromium-spec.ts 81 KB

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