chromium-spec.ts 84 KB

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