chromium-spec.ts 58 KB

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