chromium-spec.ts 79 KB

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