chromium-spec.ts 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  1. import { expect } from 'chai';
  2. import { BrowserWindow, WebContents, session, ipcMain, app, protocol, webContents } from 'electron';
  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 } from './spec-helpers';
  14. import { AddressInfo } from 'net';
  15. const features = process.electronBinding('features');
  16. const fixturesPath = path.resolve(__dirname, '..', 'spec', 'fixtures');
  17. describe('reporting api', () => {
  18. it('sends a report for a deprecation', async () => {
  19. const reports = new EventEmitter();
  20. // The Reporting API only works on https with valid certs. To dodge having
  21. // to set up a trusted certificate, hack the validator.
  22. session.defaultSession.setCertificateVerifyProc((req, cb) => {
  23. cb(0);
  24. });
  25. const certPath = path.join(fixturesPath, 'certificates');
  26. const options = {
  27. key: fs.readFileSync(path.join(certPath, 'server.key')),
  28. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  29. ca: [
  30. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  31. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  32. ],
  33. requestCert: true,
  34. rejectUnauthorized: false
  35. };
  36. const server = https.createServer(options, (req, res) => {
  37. if (req.url === '/report') {
  38. let data = '';
  39. req.on('data', (d) => { data += d.toString('utf-8'); });
  40. req.on('end', () => {
  41. reports.emit('report', JSON.parse(data));
  42. });
  43. }
  44. res.setHeader('Report-To', JSON.stringify({
  45. group: 'default',
  46. max_age: 120,
  47. endpoints: [ { url: `https://localhost:${(server.address() as any).port}/report` } ]
  48. }));
  49. res.setHeader('Content-Type', 'text/html');
  50. // using the deprecated `webkitRequestAnimationFrame` will trigger a
  51. // "deprecation" report.
  52. res.end('<script>webkitRequestAnimationFrame(() => {})</script>');
  53. });
  54. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  55. const bw = new BrowserWindow({
  56. show: false
  57. });
  58. try {
  59. const reportGenerated = emittedOnce(reports, 'report');
  60. const url = `https://localhost:${(server.address() as any).port}/a`;
  61. await bw.loadURL(url);
  62. const [report] = await reportGenerated;
  63. expect(report).to.be.an('array');
  64. expect(report[0].type).to.equal('deprecation');
  65. expect(report[0].url).to.equal(url);
  66. expect(report[0].body.id).to.equal('PrefixedRequestAnimationFrame');
  67. } finally {
  68. bw.destroy();
  69. server.close();
  70. }
  71. });
  72. });
  73. describe('window.postMessage', () => {
  74. afterEach(async () => {
  75. await closeAllWindows();
  76. });
  77. it('sets the source and origin correctly', async () => {
  78. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  79. w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`);
  80. const [, message] = await emittedOnce(ipcMain, 'complete');
  81. expect(message.data).to.equal('testing');
  82. expect(message.origin).to.equal('file://');
  83. expect(message.sourceEqualsOpener).to.equal(true);
  84. expect(message.eventOrigin).to.equal('file://');
  85. });
  86. });
  87. describe('focus handling', () => {
  88. let webviewContents: WebContents = null as unknown as WebContents;
  89. let w: BrowserWindow = null as unknown as BrowserWindow;
  90. beforeEach(async () => {
  91. w = new BrowserWindow({
  92. show: true,
  93. webPreferences: {
  94. nodeIntegration: true,
  95. webviewTag: true
  96. }
  97. });
  98. const webviewReady = emittedOnce(w.webContents, 'did-attach-webview');
  99. await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html'));
  100. const [, wvContents] = await webviewReady;
  101. webviewContents = wvContents;
  102. await emittedOnce(webviewContents, 'did-finish-load');
  103. w.focus();
  104. });
  105. afterEach(() => {
  106. webviewContents = null as unknown as WebContents;
  107. w.destroy();
  108. w = null as unknown as BrowserWindow;
  109. });
  110. const expectFocusChange = async () => {
  111. const [, focusedElementId] = await emittedOnce(ipcMain, 'focus-changed');
  112. return focusedElementId;
  113. };
  114. describe('a TAB press', () => {
  115. const tabPressEvent: any = {
  116. type: 'keyDown',
  117. keyCode: 'Tab'
  118. };
  119. it('moves focus to the next focusable item', async () => {
  120. let focusChange = expectFocusChange();
  121. w.webContents.sendInputEvent(tabPressEvent);
  122. let focusedElementId = await focusChange;
  123. expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`);
  124. focusChange = expectFocusChange();
  125. w.webContents.sendInputEvent(tabPressEvent);
  126. focusedElementId = await focusChange;
  127. expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
  128. focusChange = expectFocusChange();
  129. w.webContents.sendInputEvent(tabPressEvent);
  130. focusedElementId = await focusChange;
  131. expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
  132. focusChange = expectFocusChange();
  133. webviewContents.sendInputEvent(tabPressEvent);
  134. focusedElementId = await focusChange;
  135. expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
  136. focusChange = expectFocusChange();
  137. webviewContents.sendInputEvent(tabPressEvent);
  138. focusedElementId = await focusChange;
  139. expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`);
  140. focusChange = expectFocusChange();
  141. w.webContents.sendInputEvent(tabPressEvent);
  142. focusedElementId = await focusChange;
  143. expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`);
  144. });
  145. });
  146. describe('a SHIFT + TAB press', () => {
  147. const shiftTabPressEvent: any = {
  148. type: 'keyDown',
  149. modifiers: ['Shift'],
  150. keyCode: 'Tab'
  151. };
  152. it('moves focus to the previous focusable item', async () => {
  153. let focusChange = expectFocusChange();
  154. w.webContents.sendInputEvent(shiftTabPressEvent);
  155. let focusedElementId = await focusChange;
  156. expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`);
  157. focusChange = expectFocusChange();
  158. w.webContents.sendInputEvent(shiftTabPressEvent);
  159. focusedElementId = await focusChange;
  160. expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
  161. focusChange = expectFocusChange();
  162. webviewContents.sendInputEvent(shiftTabPressEvent);
  163. focusedElementId = await focusChange;
  164. expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
  165. focusChange = expectFocusChange();
  166. webviewContents.sendInputEvent(shiftTabPressEvent);
  167. focusedElementId = await focusChange;
  168. expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
  169. focusChange = expectFocusChange();
  170. w.webContents.sendInputEvent(shiftTabPressEvent);
  171. focusedElementId = await focusChange;
  172. expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`);
  173. focusChange = expectFocusChange();
  174. w.webContents.sendInputEvent(shiftTabPressEvent);
  175. focusedElementId = await focusChange;
  176. expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`);
  177. });
  178. });
  179. });
  180. describe('web security', () => {
  181. afterEach(closeAllWindows);
  182. let server: http.Server;
  183. let serverUrl: string;
  184. before(async () => {
  185. server = http.createServer((req, res) => {
  186. res.setHeader('Content-Type', 'text/html');
  187. res.end('<body>');
  188. });
  189. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  190. serverUrl = `http://localhost:${(server.address() as any).port}`;
  191. });
  192. after(() => {
  193. server.close();
  194. });
  195. it('engages CORB when web security is not disabled', async () => {
  196. const w = new BrowserWindow({ show: true, webPreferences: { webSecurity: true, nodeIntegration: true } });
  197. const p = emittedOnce(ipcMain, 'success');
  198. await w.loadURL(`data:text/html,<script>
  199. const s = document.createElement('script')
  200. s.src = "${serverUrl}"
  201. // The script will load successfully but its body will be emptied out
  202. // by CORB, so we don't expect a syntax error.
  203. s.onload = () => { require('electron').ipcRenderer.send('success') }
  204. document.documentElement.appendChild(s)
  205. </script>`);
  206. await p;
  207. });
  208. it('bypasses CORB when web security is disabled', async () => {
  209. const w = new BrowserWindow({ show: true, webPreferences: { webSecurity: false, nodeIntegration: true } });
  210. const p = emittedOnce(ipcMain, 'success');
  211. await w.loadURL(`data:text/html,
  212. <script>
  213. window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) }
  214. </script>
  215. <script src="${serverUrl}"></script>`);
  216. await p;
  217. });
  218. it('engages CORS when web security is not disabled', async () => {
  219. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true } });
  220. const p = emittedOnce(ipcMain, 'response');
  221. await w.loadURL(`data:text/html,<script>
  222. (async function() {
  223. try {
  224. await fetch('${serverUrl}');
  225. require('electron').ipcRenderer.send('response', 'passed');
  226. } catch {
  227. require('electron').ipcRenderer.send('response', 'failed');
  228. }
  229. })();
  230. </script>`);
  231. const [, response] = await p;
  232. expect(response).to.equal('failed');
  233. });
  234. it('bypasses CORS when web security is disabled', async () => {
  235. const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true } });
  236. const p = emittedOnce(ipcMain, 'response');
  237. await w.loadURL(`data:text/html,<script>
  238. (async function() {
  239. try {
  240. await fetch('${serverUrl}');
  241. require('electron').ipcRenderer.send('response', 'passed');
  242. } catch {
  243. require('electron').ipcRenderer.send('response', 'failed');
  244. }
  245. })();
  246. </script>`);
  247. const [, response] = await p;
  248. expect(response).to.equal('passed');
  249. });
  250. it('does not crash when multiple WebContent are created with web security disabled', () => {
  251. const options = { webPreferences: { webSecurity: false } };
  252. const w1 = new BrowserWindow(options);
  253. w1.loadURL(serverUrl);
  254. const w2 = new BrowserWindow(options);
  255. w2.loadURL(serverUrl);
  256. });
  257. });
  258. describe('command line switches', () => {
  259. describe('--lang switch', () => {
  260. const currentLocale = app.getLocale();
  261. const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
  262. const appPath = path.join(fixturesPath, 'api', 'locale-check');
  263. const args = [appPath, `--set-lang=${locale}`];
  264. if (printEnv) {
  265. args.push('--print-env');
  266. }
  267. const appProcess = ChildProcess.spawn(process.execPath, args);
  268. let output = '';
  269. appProcess.stdout.on('data', (data) => { output += data; });
  270. await emittedOnce(appProcess.stdout, 'end');
  271. output = output.replace(/(\r\n|\n|\r)/gm, '');
  272. expect(output).to.equal(result);
  273. };
  274. it('should set the locale', async () => testLocale('fr', 'fr'));
  275. it('should not set an invalid locale', async () => testLocale('asdfkl', currentLocale));
  276. const lcAll = String(process.env.LC_ALL);
  277. ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
  278. // The LC_ALL env should not be set to DOM locale string.
  279. expect(lcAll).to.not.equal(app.getLocale());
  280. });
  281. ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
  282. ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
  283. ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
  284. });
  285. describe('--remote-debugging-port switch', () => {
  286. it('should display the discovery page', (done) => {
  287. const electronPath = process.execPath;
  288. let output = '';
  289. const appProcess = ChildProcess.spawn(electronPath, [`--remote-debugging-port=`]);
  290. appProcess.stderr.on('data', (data) => {
  291. output += data;
  292. const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
  293. if (m) {
  294. appProcess.stderr.removeAllListeners('data');
  295. const port = m[1];
  296. http.get(`http://127.0.0.1:${port}`, (res) => {
  297. res.destroy();
  298. appProcess.kill();
  299. expect(res.statusCode).to.eql(200);
  300. expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
  301. done();
  302. });
  303. }
  304. });
  305. });
  306. });
  307. });
  308. describe('chromium features', () => {
  309. afterEach(closeAllWindows);
  310. describe('accessing key names also used as Node.js module names', () => {
  311. it('does not crash', (done) => {
  312. const w = new BrowserWindow({ show: false });
  313. w.webContents.once('did-finish-load', () => { done(); });
  314. w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
  315. w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
  316. });
  317. });
  318. describe('loading jquery', () => {
  319. it('does not crash', (done) => {
  320. const w = new BrowserWindow({ show: false });
  321. w.webContents.once('did-finish-load', () => { done(); });
  322. w.webContents.once('crashed', () => done(new Error('WebContents crashed.')));
  323. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
  324. });
  325. });
  326. describe('navigator.languages', () => {
  327. it('should return the system locale only', async () => {
  328. const appLocale = app.getLocale();
  329. const w = new BrowserWindow({ show: false });
  330. await w.loadURL('about:blank');
  331. const languages = await w.webContents.executeJavaScript('navigator.languages');
  332. expect(languages.length).to.be.greaterThan(0);
  333. expect(languages).to.contain(appLocale);
  334. });
  335. });
  336. describe('navigator.serviceWorker', () => {
  337. it('should register for file scheme', (done) => {
  338. const w = new BrowserWindow({
  339. show: false,
  340. webPreferences: {
  341. nodeIntegration: true,
  342. partition: 'sw-file-scheme-spec'
  343. }
  344. });
  345. w.webContents.on('ipc-message', (event, channel, message) => {
  346. if (channel === 'reload') {
  347. w.webContents.reload();
  348. } else if (channel === 'error') {
  349. done(message);
  350. } else if (channel === 'response') {
  351. expect(message).to.equal('Hello from serviceWorker!');
  352. session.fromPartition('sw-file-scheme-spec').clearStorageData({
  353. storages: ['serviceworkers']
  354. }).then(() => done());
  355. }
  356. });
  357. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  358. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  359. });
  360. it('should register for intercepted file scheme', (done) => {
  361. const customSession = session.fromPartition('intercept-file');
  362. customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
  363. let file = url.parse(request.url).pathname!;
  364. if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
  365. const content = fs.readFileSync(path.normalize(file));
  366. const ext = path.extname(file);
  367. let type = 'text/html';
  368. if (ext === '.js') type = 'application/javascript';
  369. callback({ data: content, mimeType: type } as any);
  370. }, (error) => {
  371. if (error) done(error);
  372. });
  373. const w = new BrowserWindow({
  374. show: false,
  375. webPreferences: {
  376. nodeIntegration: true,
  377. session: customSession
  378. }
  379. });
  380. w.webContents.on('ipc-message', (event, channel, message) => {
  381. if (channel === 'reload') {
  382. w.webContents.reload();
  383. } else if (channel === 'error') {
  384. done(`unexpected error : ${message}`);
  385. } else if (channel === 'response') {
  386. expect(message).to.equal('Hello from serviceWorker!');
  387. customSession.clearStorageData({
  388. storages: ['serviceworkers']
  389. }).then(() => {
  390. customSession.protocol.uninterceptProtocol('file', error => done(error));
  391. });
  392. }
  393. });
  394. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  395. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  396. });
  397. it('should not crash when nodeIntegration is enabled', (done) => {
  398. const w = new BrowserWindow({
  399. show: false,
  400. webPreferences: {
  401. nodeIntegration: true,
  402. nodeIntegrationInWorker: true,
  403. partition: 'sw-file-scheme-worker-spec'
  404. }
  405. });
  406. w.webContents.on('ipc-message', (event, channel, message) => {
  407. if (channel === 'reload') {
  408. w.webContents.reload();
  409. } else if (channel === 'error') {
  410. done(`unexpected error : ${message}`);
  411. } else if (channel === 'response') {
  412. expect(message).to.equal('Hello from serviceWorker!');
  413. session.fromPartition('sw-file-scheme-worker-spec').clearStorageData({
  414. storages: ['serviceworkers']
  415. }).then(() => done());
  416. }
  417. });
  418. w.webContents.on('crashed', () => done(new Error('WebContents crashed.')));
  419. w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
  420. });
  421. });
  422. describe('navigator.geolocation', () => {
  423. before(function () {
  424. if (!features.isFakeLocationProviderEnabled()) {
  425. return this.skip();
  426. }
  427. });
  428. it('returns error when permission is denied', (done) => {
  429. const w = new BrowserWindow({
  430. show: false,
  431. webPreferences: {
  432. nodeIntegration: true,
  433. partition: 'geolocation-spec'
  434. }
  435. });
  436. w.webContents.on('ipc-message', (event, channel) => {
  437. if (channel === 'success') {
  438. done();
  439. } else {
  440. done('unexpected response from geolocation api');
  441. }
  442. });
  443. w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
  444. if (permission === 'geolocation') {
  445. callback(false);
  446. } else {
  447. callback(true);
  448. }
  449. });
  450. w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
  451. });
  452. });
  453. describe('form submit', () => {
  454. let server: http.Server;
  455. let serverUrl: string;
  456. before(async () => {
  457. server = http.createServer((req, res) => {
  458. let body = '';
  459. req.on('data', (chunk) => {
  460. body += chunk;
  461. });
  462. res.setHeader('Content-Type', 'application/json');
  463. req.on('end', () => {
  464. res.end(`body:${body}`);
  465. });
  466. });
  467. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  468. serverUrl = `http://localhost:${(server.address() as any).port}`;
  469. });
  470. after(async () => {
  471. server.close();
  472. await closeAllWindows();
  473. });
  474. [true, false].forEach((isSandboxEnabled) =>
  475. describe(`sandbox=${isSandboxEnabled}`, () => {
  476. it('posts data in the same window', () => {
  477. const w = new BrowserWindow({
  478. show: false,
  479. webPreferences: {
  480. sandbox: isSandboxEnabled
  481. }
  482. });
  483. return new Promise(async (resolve) => {
  484. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  485. w.webContents.once('did-finish-load', async () => {
  486. const res = await w.webContents.executeJavaScript('document.body.innerText');
  487. expect(res).to.equal('body:greeting=hello');
  488. resolve();
  489. });
  490. w.webContents.executeJavaScript(`
  491. const form = document.querySelector('form')
  492. form.action = '${serverUrl}';
  493. form.submit();
  494. `);
  495. });
  496. });
  497. it('posts data to a new window with target=_blank', () => {
  498. const w = new BrowserWindow({
  499. show: false,
  500. webPreferences: {
  501. sandbox: isSandboxEnabled
  502. }
  503. });
  504. return new Promise(async (resolve) => {
  505. await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
  506. app.once('browser-window-created', async (event, newWin) => {
  507. const res = await newWin.webContents.executeJavaScript('document.body.innerText');
  508. expect(res).to.equal('body:greeting=hello');
  509. resolve();
  510. });
  511. w.webContents.executeJavaScript(`
  512. const form = document.querySelector('form')
  513. form.action = '${serverUrl}';
  514. form.target = '_blank';
  515. form.submit();
  516. `);
  517. });
  518. });
  519. })
  520. );
  521. });
  522. describe('window.open', () => {
  523. for (const show of [true, false]) {
  524. it(`inherits parent visibility over parent {show=${show}} option`, (done) => {
  525. const w = new BrowserWindow({ show });
  526. // toggle visibility
  527. if (show) {
  528. w.hide();
  529. } else {
  530. w.show();
  531. }
  532. w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
  533. expect(options.show).to.equal(w.isVisible());
  534. w.close();
  535. done();
  536. });
  537. w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
  538. });
  539. }
  540. it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
  541. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  542. w.loadURL('about:blank');
  543. w.webContents.executeJavaScript(`
  544. b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no')
  545. `);
  546. const [, contents] = await emittedOnce(app, 'web-contents-created');
  547. const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
  548. expect(typeofProcessGlobal).to.equal('undefined');
  549. });
  550. it('disables JavaScript when it is disabled on the parent window', async () => {
  551. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  552. w.webContents.loadURL('about:blank');
  553. const windowUrl = require('url').format({
  554. pathname: `${fixturesPath}/pages/window-no-javascript.html`,
  555. protocol: 'file',
  556. slashes: true
  557. });
  558. w.webContents.executeJavaScript(`
  559. b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no')
  560. `);
  561. const [, contents] = await emittedOnce(app, 'web-contents-created');
  562. await emittedOnce(contents, 'did-finish-load');
  563. // Click link on page
  564. contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
  565. contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
  566. const [, window] = await emittedOnce(app, 'browser-window-created');
  567. const preferences = (window.webContents as any).getLastWebPreferences();
  568. expect(preferences.javascript).to.be.false();
  569. });
  570. it('handles cycles when merging the parent options into the child options', (done) => {
  571. const foo = {} as any;
  572. foo.bar = foo;
  573. foo.baz = {
  574. hello: {
  575. world: true
  576. }
  577. };
  578. foo.baz2 = foo.baz;
  579. const w = new BrowserWindow({ show: false, foo: foo } as any);
  580. w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
  581. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  582. expect(options.show).to.be.false();
  583. expect((options as any).foo).to.deep.equal({
  584. bar: undefined,
  585. baz: {
  586. hello: {
  587. world: true
  588. }
  589. },
  590. baz2: {
  591. hello: {
  592. world: true
  593. }
  594. }
  595. });
  596. done();
  597. });
  598. });
  599. it('defines a window.location getter', async () => {
  600. let targetURL: string;
  601. if (process.platform === 'win32') {
  602. targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
  603. } else {
  604. targetURL = `file://${fixturesPath}/pages/base-page.html`;
  605. }
  606. const w = new BrowserWindow({ show: false });
  607. w.loadURL('about:blank');
  608. w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
  609. const [, window] = await emittedOnce(app, 'browser-window-created');
  610. await emittedOnce(window.webContents, 'did-finish-load');
  611. expect(await w.webContents.executeJavaScript(`b.location.href`)).to.equal(targetURL);
  612. });
  613. it('defines a window.location setter', async () => {
  614. const w = new BrowserWindow({ show: false });
  615. w.loadURL('about:blank');
  616. w.webContents.executeJavaScript(`{ b = window.open("about:blank"); null }`);
  617. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  618. await emittedOnce(webContents, 'did-finish-load');
  619. // When it loads, redirect
  620. w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  621. await emittedOnce(webContents, 'did-finish-load');
  622. });
  623. it('defines a window.location.href setter', async () => {
  624. const w = new BrowserWindow({ show: false });
  625. w.loadURL('about:blank');
  626. w.webContents.executeJavaScript(`{ b = window.open("about:blank"); null }`);
  627. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  628. await emittedOnce(webContents, 'did-finish-load');
  629. // When it loads, redirect
  630. w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
  631. await emittedOnce(webContents, 'did-finish-load');
  632. });
  633. it('open a blank page when no URL is specified', async () => {
  634. const w = new BrowserWindow({ show: false });
  635. w.loadURL('about:blank');
  636. w.webContents.executeJavaScript(`{ b = window.open(); null }`);
  637. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  638. await emittedOnce(webContents, 'did-finish-load');
  639. expect(await w.webContents.executeJavaScript(`b.location.href`)).to.equal('about:blank');
  640. });
  641. it('open a blank page when an empty URL is specified', async () => {
  642. const w = new BrowserWindow({ show: false });
  643. w.loadURL('about:blank');
  644. w.webContents.executeJavaScript(`{ b = window.open(''); null }`);
  645. const [, { webContents }] = await emittedOnce(app, 'browser-window-created');
  646. await emittedOnce(webContents, 'did-finish-load');
  647. expect(await w.webContents.executeJavaScript(`b.location.href`)).to.equal('about:blank');
  648. });
  649. it('sets the window title to the specified frameName', async () => {
  650. const w = new BrowserWindow({ show: false });
  651. w.loadURL('about:blank');
  652. w.webContents.executeJavaScript(`{ b = window.open('', 'hello'); null }`);
  653. const [, window] = await emittedOnce(app, 'browser-window-created');
  654. expect(window.getTitle()).to.equal('hello');
  655. });
  656. it('does not throw an exception when the frameName is a built-in object property', async () => {
  657. const w = new BrowserWindow({ show: false });
  658. w.loadURL('about:blank');
  659. w.webContents.executeJavaScript(`{ b = window.open('', '__proto__'); null }`);
  660. const [, window] = await emittedOnce(app, 'browser-window-created');
  661. expect(window.getTitle()).to.equal('__proto__');
  662. });
  663. it('denies custom open when nativeWindowOpen: true', async () => {
  664. const w = new BrowserWindow({
  665. show: false,
  666. webPreferences: {
  667. contextIsolation: false,
  668. nodeIntegration: true,
  669. nativeWindowOpen: true
  670. }
  671. });
  672. w.loadURL('about:blank');
  673. const previousListeners = process.listeners('uncaughtException');
  674. process.removeAllListeners('uncaughtException');
  675. try {
  676. const uncaughtException = new Promise<Error>(resolve => {
  677. process.once('uncaughtException', resolve);
  678. });
  679. expect(await w.webContents.executeJavaScript(`(${function () {
  680. const ipc = process.electronBinding('ipc').ipc;
  681. return ipc.sendSync(true, 'ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_OPEN', ['', '', ''])[0];
  682. }})()`)).to.be.null();
  683. const exception = await uncaughtException;
  684. expect(exception.message).to.match(/denied: expected native window\.open/);
  685. } finally {
  686. previousListeners.forEach(l => process.on('uncaughtException', l));
  687. }
  688. });
  689. });
  690. describe('window.opener', () => {
  691. it('is null for main window', async () => {
  692. const w = new BrowserWindow({
  693. show: false,
  694. webPreferences: {
  695. nodeIntegration: true
  696. }
  697. });
  698. w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
  699. const [, channel, opener] = await emittedOnce(w.webContents, 'ipc-message');
  700. expect(channel).to.equal('opener');
  701. expect(opener).to.equal(null);
  702. });
  703. });
  704. describe('navigator.mediaDevices', () => {
  705. afterEach(closeAllWindows);
  706. afterEach(() => {
  707. session.defaultSession.setPermissionCheckHandler(null);
  708. });
  709. it('can return labels of enumerated devices', async () => {
  710. const w = new BrowserWindow({ show: false });
  711. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  712. const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))`);
  713. expect(labels.some((l: any) => l)).to.be.true();
  714. });
  715. it('does not return labels of enumerated devices when permission denied', async () => {
  716. session.defaultSession.setPermissionCheckHandler(() => false);
  717. const w = new BrowserWindow({ show: false });
  718. w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  719. const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))`);
  720. expect(labels.some((l: any) => l)).to.be.false();
  721. });
  722. it('returns the same device ids across reloads', async () => {
  723. const ses = session.fromPartition('persist:media-device-id');
  724. const w = new BrowserWindow({
  725. show: false,
  726. webPreferences: {
  727. nodeIntegration: true,
  728. session: ses
  729. }
  730. });
  731. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  732. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  733. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  734. expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
  735. });
  736. it('can return new device id when cookie storage is cleared', async () => {
  737. const ses = session.fromPartition('persist:media-device-id');
  738. const w = new BrowserWindow({
  739. show: false,
  740. webPreferences: {
  741. nodeIntegration: true,
  742. session: ses
  743. }
  744. });
  745. w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
  746. const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds');
  747. await ses.clearStorageData({ storages: ['cookies'] });
  748. const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload());
  749. expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
  750. });
  751. });
  752. describe('window.opener access', () => {
  753. const scheme = 'app';
  754. const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
  755. const httpUrl1 = `${scheme}://origin1`;
  756. const httpUrl2 = `${scheme}://origin2`;
  757. const fileBlank = `file://${fixturesPath}/pages/blank.html`;
  758. const httpBlank = `${scheme}://origin1/blank`;
  759. const table = [
  760. { parent: fileBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: false },
  761. { parent: fileBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: false },
  762. { parent: fileBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  763. { parent: fileBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: false },
  764. { parent: httpBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: false },
  765. // {parent: httpBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: false}, // can't window.open()
  766. { parent: httpBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  767. // {parent: httpBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: false}, // can't window.open()
  768. // NB. this is different from Chrome's behavior, which isolates file: urls from each other
  769. { parent: fileBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: true },
  770. { parent: fileBlank, child: fileUrl, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: true },
  771. { parent: fileBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  772. { parent: fileBlank, child: fileUrl, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: true },
  773. { parent: httpBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: true },
  774. { parent: httpBlank, child: httpUrl1, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: true },
  775. { parent: httpBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  776. { parent: httpBlank, child: httpUrl1, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: true },
  777. { parent: httpBlank, child: httpUrl2, nodeIntegration: false, nativeWindowOpen: false, openerAccessible: false },
  778. { parent: httpBlank, child: httpUrl2, nodeIntegration: false, nativeWindowOpen: true, openerAccessible: false },
  779. { parent: httpBlank, child: httpUrl2, nodeIntegration: true, nativeWindowOpen: false, openerAccessible: true },
  780. { parent: httpBlank, child: httpUrl2, nodeIntegration: true, nativeWindowOpen: true, openerAccessible: false }
  781. ];
  782. const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
  783. before(async () => {
  784. await promisify(protocol.registerFileProtocol)(scheme, (request, callback) => {
  785. if (request.url.includes('blank')) {
  786. callback(`${fixturesPath}/pages/blank.html`);
  787. } else {
  788. callback(`${fixturesPath}/pages/window-opener-location.html`);
  789. }
  790. });
  791. });
  792. after(async () => {
  793. await promisify(protocol.unregisterProtocol)(scheme);
  794. });
  795. afterEach(closeAllWindows);
  796. describe('when opened from main window', () => {
  797. for (const { parent, child, nodeIntegration, nativeWindowOpen, openerAccessible } of table) {
  798. for (const sandboxPopup of [false, true]) {
  799. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} nativeWindowOpen=${nativeWindowOpen} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  800. it(description, async () => {
  801. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nativeWindowOpen } });
  802. w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
  803. options!.webPreferences!.sandbox = sandboxPopup;
  804. });
  805. await w.loadURL(parent);
  806. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
  807. window.addEventListener('message', function f(e) {
  808. resolve(e.data)
  809. })
  810. window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
  811. })`);
  812. if (openerAccessible) {
  813. expect(childOpenerLocation).to.be.a('string');
  814. } else {
  815. expect(childOpenerLocation).to.be.null();
  816. }
  817. });
  818. }
  819. }
  820. });
  821. describe('when opened from <webview>', () => {
  822. for (const { parent, child, nodeIntegration, nativeWindowOpen, openerAccessible } of table) {
  823. const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} nativeWindowOpen=${nativeWindowOpen}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
  824. // WebView erroneously allows access to the parent window when nativeWindowOpen is false.
  825. const skip = !nativeWindowOpen && !openerAccessible;
  826. ifit(!skip)(description, async () => {
  827. // This test involves three contexts:
  828. // 1. The root BrowserWindow in which the test is run,
  829. // 2. A <webview> belonging to the root window,
  830. // 3. A window opened by calling window.open() from within the <webview>.
  831. // We are testing whether context (3) can access context (2) under various conditions.
  832. // This is context (1), the base window for the test.
  833. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true } });
  834. await w.loadURL('about:blank');
  835. const parentCode = `new Promise((resolve) => {
  836. // This is context (3), a child window of the WebView.
  837. const child = window.open(${JSON.stringify(child)}, "", "show=no")
  838. window.addEventListener("message", e => {
  839. resolve(e.data)
  840. })
  841. })`;
  842. const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  843. // This is context (2), a WebView which will call window.open()
  844. const webview = new WebView()
  845. webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
  846. webview.setAttribute('webpreferences', 'nativeWindowOpen=${nativeWindowOpen ? 'yes' : 'no'}')
  847. webview.setAttribute('allowpopups', 'on')
  848. webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
  849. webview.addEventListener('dom-ready', async () => {
  850. webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
  851. })
  852. document.body.appendChild(webview)
  853. })`);
  854. if (openerAccessible) {
  855. expect(childOpenerLocation).to.be.a('string');
  856. } else {
  857. expect(childOpenerLocation).to.be.null();
  858. }
  859. });
  860. }
  861. });
  862. });
  863. describe('storage', () => {
  864. describe('custom non standard schemes', () => {
  865. const protocolName = 'storage';
  866. let contents: WebContents;
  867. before((done) => {
  868. protocol.registerFileProtocol(protocolName, (request, callback) => {
  869. const parsedUrl = url.parse(request.url);
  870. let filename;
  871. switch (parsedUrl.pathname) {
  872. case '/localStorage' : filename = 'local_storage.html'; break;
  873. case '/sessionStorage' : filename = 'session_storage.html'; break;
  874. case '/WebSQL' : filename = 'web_sql.html'; break;
  875. case '/indexedDB' : filename = 'indexed_db.html'; break;
  876. case '/cookie' : filename = 'cookie.html'; break;
  877. default : filename = '';
  878. }
  879. callback({ path: `${fixturesPath}/pages/storage/${filename}` });
  880. }, (error) => done(error));
  881. });
  882. after((done) => {
  883. protocol.unregisterProtocol(protocolName, () => done());
  884. });
  885. beforeEach(() => {
  886. contents = (webContents as any).create({
  887. nodeIntegration: true
  888. });
  889. });
  890. afterEach(() => {
  891. (contents as any).destroy();
  892. contents = null as any;
  893. });
  894. it('cannot access localStorage', (done) => {
  895. ipcMain.once('local-storage-response', (event, error) => {
  896. expect(error).to.equal(`Failed to read the 'localStorage' property from 'Window': Access is denied for this document.`);
  897. done();
  898. });
  899. contents.loadURL(protocolName + '://host/localStorage');
  900. });
  901. it('cannot access sessionStorage', (done) => {
  902. ipcMain.once('session-storage-response', (event, error) => {
  903. expect(error).to.equal(`Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document.`);
  904. done();
  905. });
  906. contents.loadURL(`${protocolName}://host/sessionStorage`);
  907. });
  908. it('cannot access WebSQL database', (done) => {
  909. ipcMain.once('web-sql-response', (event, error) => {
  910. expect(error).to.equal(`Failed to execute 'openDatabase' on 'Window': Access to the WebDatabase API is denied in this context.`);
  911. done();
  912. });
  913. contents.loadURL(`${protocolName}://host/WebSQL`);
  914. });
  915. it('cannot access indexedDB', (done) => {
  916. ipcMain.once('indexed-db-response', (event, error) => {
  917. expect(error).to.equal(`Failed to execute 'open' on 'IDBFactory': access to the Indexed Database API is denied in this context.`);
  918. done();
  919. });
  920. contents.loadURL(`${protocolName}://host/indexedDB`);
  921. });
  922. it('cannot access cookie', (done) => {
  923. ipcMain.once('cookie-response', (event, error) => {
  924. expect(error).to.equal(`Failed to set the 'cookie' property on 'Document': Access is denied for this document.`);
  925. done();
  926. });
  927. contents.loadURL(`${protocolName}://host/cookie`);
  928. });
  929. });
  930. describe('can be accessed', () => {
  931. let server: http.Server;
  932. let serverUrl: string;
  933. let serverCrossSiteUrl: string;
  934. before((done) => {
  935. server = http.createServer((req, res) => {
  936. const respond = () => {
  937. if (req.url === '/redirect-cross-site') {
  938. res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
  939. res.statusCode = 302;
  940. res.end();
  941. } else if (req.url === '/redirected') {
  942. res.end('<html><script>window.localStorage</script></html>');
  943. } else {
  944. res.end();
  945. }
  946. };
  947. setTimeout(respond, 0);
  948. });
  949. server.listen(0, '127.0.0.1', () => {
  950. serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  951. serverCrossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`;
  952. done();
  953. });
  954. });
  955. after(() => {
  956. server.close();
  957. server = null as any;
  958. });
  959. afterEach(closeAllWindows);
  960. const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
  961. it(testTitle, (done) => {
  962. const w = new BrowserWindow({
  963. show: false,
  964. ...extraPreferences
  965. });
  966. let redirected = false;
  967. w.webContents.on('crashed', () => {
  968. expect.fail('renderer crashed / was killed');
  969. });
  970. w.webContents.on('did-redirect-navigation', (event, url) => {
  971. expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
  972. redirected = true;
  973. });
  974. w.webContents.on('did-finish-load', () => {
  975. expect(redirected).to.be.true('didnt redirect');
  976. done();
  977. });
  978. w.loadURL(`${serverUrl}/redirect-cross-site`);
  979. });
  980. };
  981. testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
  982. testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
  983. });
  984. describe('enableWebSQL webpreference', () => {
  985. const standardScheme = (global as any).standardScheme;
  986. const origin = `${standardScheme}://fake-host`;
  987. const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
  988. const sqlPartition = 'web-sql-preference-test';
  989. const sqlSession = session.fromPartition(sqlPartition);
  990. const securityError = 'An attempt was made to break through the security policy of the user agent.';
  991. let contents: WebContents, w: BrowserWindow;
  992. before(() => {
  993. sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
  994. callback({ path: filePath });
  995. });
  996. });
  997. after(() => {
  998. sqlSession.protocol.unregisterProtocol(standardScheme);
  999. });
  1000. afterEach(async () => {
  1001. if (contents) {
  1002. (contents as any).destroy();
  1003. contents = null as any;
  1004. }
  1005. await closeAllWindows();
  1006. (w as any) = null;
  1007. });
  1008. it('default value allows websql', async () => {
  1009. contents = (webContents as any).create({
  1010. session: sqlSession,
  1011. nodeIntegration: true
  1012. });
  1013. contents.loadURL(origin);
  1014. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1015. expect(error).to.be.null();
  1016. });
  1017. it('when set to false can disallow websql', async () => {
  1018. contents = (webContents as any).create({
  1019. session: sqlSession,
  1020. nodeIntegration: true,
  1021. enableWebSQL: false
  1022. });
  1023. contents.loadURL(origin);
  1024. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1025. expect(error).to.equal(securityError);
  1026. });
  1027. it('when set to false does not disable indexedDB', async () => {
  1028. contents = (webContents as any).create({
  1029. session: sqlSession,
  1030. nodeIntegration: true,
  1031. enableWebSQL: false
  1032. });
  1033. contents.loadURL(origin);
  1034. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1035. expect(error).to.equal(securityError);
  1036. const dbName = 'random';
  1037. const result = await contents.executeJavaScript(`
  1038. new Promise((resolve, reject) => {
  1039. try {
  1040. let req = window.indexedDB.open('${dbName}');
  1041. req.onsuccess = (event) => {
  1042. let db = req.result;
  1043. resolve(db.name);
  1044. }
  1045. req.onerror = (event) => { resolve(event.target.code); }
  1046. } catch (e) {
  1047. resolve(e.message);
  1048. }
  1049. });
  1050. `);
  1051. expect(result).to.equal(dbName);
  1052. });
  1053. it('child webContents can override when the embedder has allowed websql', async () => {
  1054. w = new BrowserWindow({
  1055. show: false,
  1056. webPreferences: {
  1057. nodeIntegration: true,
  1058. webviewTag: true,
  1059. session: sqlSession
  1060. }
  1061. });
  1062. w.webContents.loadURL(origin);
  1063. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1064. expect(error).to.be.null();
  1065. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1066. await w.webContents.executeJavaScript(`
  1067. new Promise((resolve, reject) => {
  1068. const webview = new WebView();
  1069. webview.setAttribute('src', '${origin}');
  1070. webview.setAttribute('webpreferences', 'enableWebSQL=0');
  1071. webview.setAttribute('partition', '${sqlPartition}');
  1072. webview.setAttribute('nodeIntegration', 'on');
  1073. document.body.appendChild(webview);
  1074. webview.addEventListener('dom-ready', () => resolve());
  1075. });
  1076. `);
  1077. const [, childError] = await webviewResult;
  1078. expect(childError).to.equal(securityError);
  1079. });
  1080. it('child webContents cannot override when the embedder has disallowed websql', async () => {
  1081. w = new BrowserWindow({
  1082. show: false,
  1083. webPreferences: {
  1084. nodeIntegration: true,
  1085. enableWebSQL: false,
  1086. webviewTag: true,
  1087. session: sqlSession
  1088. }
  1089. });
  1090. w.webContents.loadURL('data:text/html,<html></html>');
  1091. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1092. await w.webContents.executeJavaScript(`
  1093. new Promise((resolve, reject) => {
  1094. const webview = new WebView();
  1095. webview.setAttribute('src', '${origin}');
  1096. webview.setAttribute('webpreferences', 'enableWebSQL=1');
  1097. webview.setAttribute('partition', '${sqlPartition}');
  1098. webview.setAttribute('nodeIntegration', 'on');
  1099. document.body.appendChild(webview);
  1100. webview.addEventListener('dom-ready', () => resolve());
  1101. });
  1102. `);
  1103. const [, childError] = await webviewResult;
  1104. expect(childError).to.equal(securityError);
  1105. });
  1106. it('child webContents can use websql when the embedder has allowed websql', async () => {
  1107. w = new BrowserWindow({
  1108. show: false,
  1109. webPreferences: {
  1110. nodeIntegration: true,
  1111. webviewTag: true,
  1112. session: sqlSession
  1113. }
  1114. });
  1115. w.webContents.loadURL(origin);
  1116. const [, error] = await emittedOnce(ipcMain, 'web-sql-response');
  1117. expect(error).to.be.null();
  1118. const webviewResult = emittedOnce(ipcMain, 'web-sql-response');
  1119. await w.webContents.executeJavaScript(`
  1120. new Promise((resolve, reject) => {
  1121. const webview = new WebView();
  1122. webview.setAttribute('src', '${origin}');
  1123. webview.setAttribute('webpreferences', 'enableWebSQL=1');
  1124. webview.setAttribute('partition', '${sqlPartition}');
  1125. webview.setAttribute('nodeIntegration', 'on');
  1126. document.body.appendChild(webview);
  1127. webview.addEventListener('dom-ready', () => resolve());
  1128. });
  1129. `);
  1130. const [, childError] = await webviewResult;
  1131. expect(childError).to.be.null();
  1132. });
  1133. });
  1134. });
  1135. ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
  1136. const pdfSource = url.format({
  1137. pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'),
  1138. protocol: 'file',
  1139. slashes: true
  1140. });
  1141. it('opens when loading a pdf resource as top level navigation', async () => {
  1142. const w = new BrowserWindow({ show: false });
  1143. w.loadURL(pdfSource);
  1144. const [, contents] = await emittedOnce(app, 'web-contents-created');
  1145. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1146. await new Promise((resolve) => {
  1147. contents.on('did-finish-load', resolve);
  1148. contents.on('did-frame-finish-load', resolve);
  1149. });
  1150. });
  1151. it('opens when loading a pdf resource in a iframe', async () => {
  1152. const w = new BrowserWindow({ show: false });
  1153. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
  1154. const [, contents] = await emittedOnce(app, 'web-contents-created');
  1155. expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
  1156. await new Promise((resolve) => {
  1157. contents.on('did-finish-load', resolve);
  1158. contents.on('did-frame-finish-load', resolve);
  1159. });
  1160. });
  1161. });
  1162. describe('window.history', () => {
  1163. describe('window.history.pushState', () => {
  1164. it('should push state after calling history.pushState() from the same url', async () => {
  1165. const w = new BrowserWindow({ show: false });
  1166. await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
  1167. // History should have current page by now.
  1168. expect((w.webContents as any).length()).to.equal(1);
  1169. const waitCommit = emittedOnce(w.webContents, 'navigation-entry-committed');
  1170. w.webContents.executeJavaScript('window.history.pushState({}, "")');
  1171. await waitCommit;
  1172. // Initial page + pushed state.
  1173. expect((w.webContents as any).length()).to.equal(2);
  1174. });
  1175. });
  1176. });
  1177. describe('chrome://media-internals', () => {
  1178. it('loads the page successfully', async () => {
  1179. const w = new BrowserWindow({ show: false });
  1180. w.loadURL('chrome://media-internals');
  1181. const pageExists = await w.webContents.executeJavaScript(
  1182. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1183. );
  1184. expect(pageExists).to.be.true();
  1185. });
  1186. });
  1187. describe('chrome://webrtc-internals', () => {
  1188. it('loads the page successfully', async () => {
  1189. const w = new BrowserWindow({ show: false });
  1190. w.loadURL('chrome://webrtc-internals');
  1191. const pageExists = await w.webContents.executeJavaScript(
  1192. "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
  1193. );
  1194. expect(pageExists).to.be.true();
  1195. });
  1196. });
  1197. });
  1198. describe('font fallback', () => {
  1199. async function getRenderedFonts (html: string) {
  1200. const w = new BrowserWindow({ show: false });
  1201. try {
  1202. await w.loadURL(`data:text/html,${html}`);
  1203. w.webContents.debugger.attach();
  1204. const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
  1205. const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
  1206. await sendCommand('CSS.enable');
  1207. const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
  1208. return fonts;
  1209. } finally {
  1210. w.close();
  1211. }
  1212. }
  1213. it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
  1214. const html = `<body style="font-family: sans-serif">test</body>`;
  1215. const fonts = await getRenderedFonts(html);
  1216. expect(fonts).to.be.an('array');
  1217. expect(fonts).to.have.length(1);
  1218. if (process.platform === 'win32') { expect(fonts[0].familyName).to.equal('Arial'); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Helvetica'); } else if (process.platform === 'linux') { expect(fonts[0].familyName).to.equal('DejaVu Sans'); } // I think this depends on the distro? We don't specify a default.
  1219. });
  1220. ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
  1221. const html = `
  1222. <html lang="ja-JP">
  1223. <head>
  1224. <meta charset="utf-8" />
  1225. </head>
  1226. <body style="font-family: sans-serif">test 智史</body>
  1227. </html>
  1228. `;
  1229. const fonts = await getRenderedFonts(html);
  1230. expect(fonts).to.be.an('array');
  1231. expect(fonts).to.have.length(1);
  1232. 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'); }
  1233. });
  1234. });
  1235. describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
  1236. const fullscreenChildHtml = promisify(fs.readFile)(
  1237. path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
  1238. );
  1239. let w: BrowserWindow, server: http.Server;
  1240. before(() => {
  1241. server = http.createServer(async (_req, res) => {
  1242. res.writeHead(200, { 'Content-Type': 'text/html' });
  1243. res.write(await fullscreenChildHtml);
  1244. res.end();
  1245. });
  1246. server.listen(8989, '127.0.0.1');
  1247. });
  1248. beforeEach(() => {
  1249. w = new BrowserWindow({
  1250. show: true,
  1251. fullscreen: true,
  1252. webPreferences: {
  1253. nodeIntegration: true,
  1254. nodeIntegrationInSubFrames: true
  1255. }
  1256. });
  1257. });
  1258. afterEach(async () => {
  1259. await closeAllWindows()
  1260. ;(w as any) = null;
  1261. server.close();
  1262. });
  1263. it('can fullscreen from out-of-process iframes (OOPIFs)', done => {
  1264. ipcMain.once('fullscreenChange', async () => {
  1265. const fullscreenWidth = await w.webContents.executeJavaScript(
  1266. "document.querySelector('iframe').offsetWidth"
  1267. );
  1268. expect(fullscreenWidth > 0).to.be.true();
  1269. await w.webContents.executeJavaScript(
  1270. "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
  1271. );
  1272. await new Promise(resolve => setTimeout(resolve, 500));
  1273. const width = await w.webContents.executeJavaScript(
  1274. "document.querySelector('iframe').offsetWidth"
  1275. );
  1276. expect(width).to.equal(0);
  1277. done();
  1278. });
  1279. const html =
  1280. '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>';
  1281. w.loadURL(`data:text/html,${html}`);
  1282. });
  1283. it('can fullscreen from in-process iframes', done => {
  1284. ipcMain.once('fullscreenChange', async () => {
  1285. const fullscreenWidth = await w.webContents.executeJavaScript(
  1286. "document.querySelector('iframe').offsetWidth"
  1287. );
  1288. expect(fullscreenWidth > 0).to.true();
  1289. await w.webContents.executeJavaScript('document.exitFullscreen()');
  1290. const width = await w.webContents.executeJavaScript(
  1291. "document.querySelector('iframe').offsetWidth"
  1292. );
  1293. expect(width).to.equal(0);
  1294. done();
  1295. });
  1296. w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
  1297. });
  1298. });