electron/spec/api-browser-window-spec.js

3810 lines
120 KiB
JavaScript
Raw Normal View History

2016-03-25 20:03:49 +00:00
'use strict'
2016-01-23 11:35:30 +00:00
2016-03-25 20:03:49 +00:00
const assert = require('assert')
const chai = require('chai')
const dirtyChai = require('dirty-chai')
2016-03-25 20:03:49 +00:00
const fs = require('fs')
const path = require('path')
const os = require('os')
2016-10-12 17:26:53 +00:00
const qs = require('querystring')
const http = require('http')
2018-09-13 16:10:51 +00:00
const { closeWindow } = require('./window-helpers')
const { emittedOnce } = require('./events-helpers')
const { ipcRenderer, remote } = require('electron')
const { app, ipcMain, BrowserWindow, BrowserView, protocol, session, screen, webContents } = remote
2016-01-12 02:40:23 +00:00
const features = process.electronBinding('features')
2018-09-13 16:10:51 +00:00
const { expect } = chai
2016-03-25 20:03:49 +00:00
const isCI = remote.getGlobal('isCi')
const nativeModulesEnabled = remote.getGlobal('nativeModulesEnabled')
2016-01-12 02:40:23 +00:00
chai.use(dirtyChai)
2017-11-01 14:48:09 +00:00
describe('BrowserWindow module', () => {
const fixtures = path.resolve(__dirname, 'fixtures')
let w = null
let iw = null
2017-11-01 14:48:09 +00:00
let ws = null
let server
let postData
const defaultOptions = {
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false,
nodeIntegration: true
}
}
const openTheWindow = async (options = defaultOptions) => {
// The `afterEach` hook isn't called if a test fails,
// we should make sure that the window is closed ourselves.
await closeTheWindow()
w = new BrowserWindow(options)
return w
}
const closeTheWindow = function () {
return closeWindow(w).then(() => { w = null })
}
2017-11-01 14:48:09 +00:00
before((done) => {
2016-10-12 17:26:53 +00:00
const filePath = path.join(fixtures, 'pages', 'a.html')
const fileStats = fs.statSync(filePath)
postData = [
{
2016-11-11 17:22:45 +00:00
type: 'rawData',
bytes: Buffer.from('username=test&file=')
2016-10-12 17:26:53 +00:00
},
{
2016-11-11 17:22:45 +00:00
type: 'file',
filePath: filePath,
offset: 0,
length: fileStats.size,
modificationTime: fileStats.mtime.getTime() / 1000
2016-10-12 17:26:53 +00:00
}
]
2017-11-01 14:48:09 +00:00
server = http.createServer((req, res) => {
2016-10-12 17:26:53 +00:00
function respond () {
if (req.method === 'POST') {
let body = ''
req.on('data', (data) => {
2017-11-01 14:48:09 +00:00
if (data) body += data
2016-10-12 17:26:53 +00:00
})
req.on('end', () => {
const parsedData = qs.parse(body)
2016-10-12 17:26:53 +00:00
fs.readFile(filePath, (err, data) => {
if (err) return
if (parsedData.username === 'test' &&
parsedData.file === data.toString()) {
res.end()
}
})
})
} else if (req.url === '/302') {
res.setHeader('Location', '/200')
res.statusCode = 302
res.end()
} else if (req.url === '/navigate-302') {
res.end(`<html><body><script>window.location='${server.url}/302'</script></body></html>`)
fix: use appropriate site instance for cross-site nav's (#15821) * fix: use Chromium's determined new site instance as candidate when navigating. When navigating to a new address, consider using Chromium's determined site instance for the new page as it should belong to an existing browsing instance when the navigation was triggered by window.open(). fixes 8100. * Revert "fix: use Chromium's determined new site instance as candidate when navigating." This reverts commit eb95f935654a2c4d4457821297670836c10fdfd5. * fix: delegate site instance creation back to content when sandboxed. * fix: ensure site isolation is on * test: adapt ut for cross-site navigation * fix: register pending processes during a navigation. * refactor: dont call loadURL for a window constructed from an existing webContents. * test: add sandboxed affinity UT's. * fix: check affinity before deciding if to force a new site instance. * chore: adapt subsequent patch. * refactor: constify logically const methods. * fix: do not reuse site instances when navigation redirects cross-site. * test: ensure localStorage accessible after x-site redirect. * test: adapt localStorage acess denied UT for site isolation. * fix: do not send render-view-deleted for speculative frames. * chore: amend tests after rebase. * test: add ut for webContents' render-view-deleted emission * fix: introduce current-render-view-deleted for current RVH's deletions. Revert render-view-deleted to being emitted with any RVH's deletion. current-render-view-deleted is emitted only when the RVH being deleted is the current one. * refactor: style and comments fixed.
2018-12-05 08:03:39 +00:00
} else if (req.url === '/cross-site') {
res.end(`<html><body><h1>${req.url}</h1></body></html>`)
2016-10-12 17:26:53 +00:00
} else {
res.end()
}
}
setTimeout(respond, req.url.includes('slow') ? 200 : 0)
2016-06-29 16:37:10 +00:00
})
2017-11-01 14:48:09 +00:00
server.listen(0, '127.0.0.1', () => {
server.url = `http://127.0.0.1:${server.address().port}`
done()
})
})
2017-11-01 14:48:09 +00:00
after(() => {
server.close()
server = null
})
beforeEach(openTheWindow)
afterEach(closeTheWindow)
2016-03-25 20:03:49 +00:00
describe('BrowserWindow constructor', () => {
it('allows passing void 0 as the webContents', async () => {
await openTheWindow({
webContents: void 0
})
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.close()', () => {
2017-04-05 06:30:36 +00:00
let server
2017-11-01 14:48:09 +00:00
before((done) => {
2017-04-05 06:30:36 +00:00
server = http.createServer((request, response) => {
switch (request.url) {
case '/404':
response.statusCode = '404'
response.end()
break
case '/301':
response.statusCode = '301'
response.setHeader('Location', '/200')
response.end()
break
case '/200':
response.statusCode = '200'
response.end('hello')
break
case '/title':
response.statusCode = '200'
response.end('<title>Hello</title>')
break
2017-04-05 06:30:36 +00:00
default:
done('unsupported endpoint')
}
}).listen(0, '127.0.0.1', () => {
server.url = 'http://127.0.0.1:' + server.address().port
done()
})
})
2017-11-01 14:48:09 +00:00
after(() => {
2017-04-05 06:30:36 +00:00
server.close()
server = null
})
2017-11-01 14:48:09 +00:00
it('should emit unload handler', (done) => {
w.webContents.once('did-finish-load', () => { w.close() })
2017-11-01 14:48:09 +00:00
w.once('closed', () => {
const test = path.join(fixtures, 'api', 'unload')
const content = fs.readFileSync(test)
2016-03-25 20:03:49 +00:00
fs.unlinkSync(test)
2018-09-13 16:10:51 +00:00
assert.strictEqual(String(content), 'unload')
2016-03-25 20:03:49 +00:00
done()
})
w.loadFile(path.join(fixtures, 'api', 'unload.html'))
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('should emit beforeunload handler', (done) => {
w.once('onbeforeunload', () => { done() })
w.webContents.once('did-finish-load', () => { w.close() })
w.loadFile(path.join(fixtures, 'api', 'beforeunload-false.html'))
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('should not crash when invoked synchronously inside navigation observer', (done) => {
2017-04-05 06:30:36 +00:00
const events = [
{ name: 'did-start-loading', url: `${server.url}/200` },
{ name: 'dom-ready', url: `${server.url}/200` },
{ name: 'page-title-updated', url: `${server.url}/title` },
2017-04-05 06:30:36 +00:00
{ name: 'did-stop-loading', url: `${server.url}/200` },
{ name: 'did-finish-load', url: `${server.url}/200` },
{ name: 'did-frame-finish-load', url: `${server.url}/200` },
{ name: 'did-fail-load', url: `${server.url}/404` }
]
const responseEvent = 'window-webContents-destroyed'
2017-11-23 22:22:43 +00:00
function * genNavigationEvent () {
2017-04-05 06:30:36 +00:00
let eventOptions = null
while ((eventOptions = events.shift()) && events.length) {
const w = new BrowserWindow({ show: false })
2017-04-05 06:30:36 +00:00
eventOptions.id = w.id
eventOptions.responseEvent = responseEvent
ipcRenderer.send('test-webcontents-navigation-observer', eventOptions)
yield 1
}
}
const gen = genNavigationEvent()
2017-11-01 14:48:09 +00:00
ipcRenderer.on(responseEvent, () => {
2017-04-05 06:30:36 +00:00
if (!gen.next().value) done()
})
gen.next()
})
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
describe('window.close()', () => {
it('should emit unload handler', (done) => {
w.once('closed', () => {
const test = path.join(fixtures, 'api', 'close')
const content = fs.readFileSync(test)
2016-03-25 20:03:49 +00:00
fs.unlinkSync(test)
2018-09-13 16:10:51 +00:00
assert.strictEqual(String(content), 'close')
2016-03-25 20:03:49 +00:00
done()
})
w.loadFile(path.join(fixtures, 'api', 'close.html'))
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('should emit beforeunload handler', (done) => {
w.once('onbeforeunload', () => { done() })
w.loadFile(path.join(fixtures, 'api', 'close-beforeunload-false.html'))
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.destroy()', () => {
it('prevents users to access methods of webContents', () => {
const contents = w.webContents
2016-03-25 20:03:49 +00:00
w.destroy()
2017-11-01 14:48:09 +00:00
assert.throws(() => {
contents.getProcessId()
2016-03-29 00:16:08 +00:00
}, /Object has been destroyed/)
2016-03-25 20:03:49 +00:00
})
it('should not crash when destroying windows with pending events', (done) => {
const responseEvent = 'destroy-test-completed'
ipcRenderer.on(responseEvent, () => done())
ipcRenderer.send('test-browserwindow-destroy', { responseEvent })
})
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.loadURL(url)', () => {
it('should emit did-start-loading event', (done) => {
w.webContents.on('did-start-loading', () => { done() })
2016-03-25 20:03:49 +00:00
w.loadURL('about:blank')
})
2017-11-01 14:48:09 +00:00
it('should emit ready-to-show event', (done) => {
w.on('ready-to-show', () => { done() })
2016-10-31 19:40:49 +00:00
w.loadURL('about:blank')
})
2017-11-01 14:48:09 +00:00
it('should emit did-fail-load event for files that do not exist', (done) => {
w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(code, -6)
assert.strictEqual(desc, 'ERR_FILE_NOT_FOUND')
assert.strictEqual(isMainFrame, true)
2016-03-25 20:03:49 +00:00
done()
})
w.loadURL('file://a.txt')
})
2017-11-01 14:48:09 +00:00
it('should emit did-fail-load event for invalid URL', (done) => {
w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(desc, 'ERR_INVALID_URL')
assert.strictEqual(code, -300)
assert.strictEqual(isMainFrame, true)
2016-03-25 20:03:49 +00:00
done()
})
w.loadURL('http://example:port')
})
2017-11-01 14:48:09 +00:00
it('should set `mainFrame = false` on did-fail-load events in iframes', (done) => {
w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(isMainFrame, false)
done()
})
w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html'))
})
2017-11-01 14:48:09 +00:00
it('does not crash in did-fail-provisional-load handler', (done) => {
w.webContents.once('did-fail-provisional-load', () => {
2016-04-30 09:21:18 +00:00
w.loadURL('http://127.0.0.1:11111')
done()
})
2016-04-30 09:21:18 +00:00
w.loadURL('http://127.0.0.1:11111')
})
2017-11-01 14:48:09 +00:00
it('should emit did-fail-load event for URL exceeding character limit', (done) => {
w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(desc, 'ERR_INVALID_URL')
assert.strictEqual(code, -300)
assert.strictEqual(isMainFrame, true)
2017-01-23 14:27:47 +00:00
done()
})
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64')
2017-01-25 08:50:33 +00:00
w.loadURL(`data:image/png;base64,${data}`)
2017-01-23 14:27:47 +00:00
})
2017-11-01 14:48:09 +00:00
describe('POST navigations', () => {
afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null) })
it('supports specifying POST data', async () => {
await w.loadURL(server.url, { postData: postData })
})
it('sets the content type header on URL encoded forms', async () => {
await w.loadURL(server.url)
const requestDetails = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
resolve(details)
})
})
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.target = '_blank'
form.submit()
`)
const details = await requestDetails
assert.strictEqual(details.requestHeaders['content-type'], 'application/x-www-form-urlencoded')
})
it('sets the content type header on multi part forms', async () => {
await w.loadURL(server.url)
const requestDetails = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
resolve(details)
})
})
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.target = '_blank'
form.enctype = 'multipart/form-data'
file = document.createElement('input')
file.type = 'file'
file.name = 'file'
form.appendChild(file)
form.submit()
`)
const details = await requestDetails
assert(details.requestHeaders['content-type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary'))
})
2016-10-12 17:26:53 +00:00
})
2017-03-02 22:37:09 +00:00
it('should support support base url for data urls', (done) => {
2017-11-01 14:48:09 +00:00
ipcMain.once('answer', (event, test) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(test, 'test')
done()
})
2018-09-13 16:10:51 +00:00
w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `file://${path.join(fixtures, 'api')}${path.sep}` })
})
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
describe('will-navigate event', () => {
it('allows the window to be closed from the event listener', (done) => {
ipcRenderer.send('close-on-will-navigate', w.id)
2017-11-01 14:48:09 +00:00
ipcRenderer.once('closed-on-will-navigate', () => { done() })
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'))
})
})
describe('will-redirect event', () => {
it('is emitted on redirects', (done) => {
w.webContents.on('will-redirect', (event, url) => {
done()
})
w.loadURL(`${server.url}/302`)
})
it('is emitted after will-navigate on redirects', (done) => {
let navigateCalled = false
w.webContents.on('will-navigate', () => {
navigateCalled = true
})
w.webContents.on('will-redirect', (event, url) => {
expect(navigateCalled).to.equal(true, 'should have called will-navigate first')
done()
})
w.loadURL(`${server.url}/navigate-302`)
})
it('is emitted before did-stop-loading on redirects', (done) => {
let stopCalled = false
w.webContents.on('did-stop-loading', () => {
stopCalled = true
})
w.webContents.on('will-redirect', (event, url) => {
expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first')
done()
})
w.loadURL(`${server.url}/302`)
})
it('allows the window to be closed from the event listener', (done) => {
ipcRenderer.send('close-on-will-redirect', w.id)
ipcRenderer.once('closed-on-will-redirect', () => { done() })
w.loadURL(`${server.url}/302`)
})
it('can be prevented', (done) => {
ipcRenderer.send('prevent-will-redirect', w.id)
w.webContents.on('will-navigate', (e, url) => {
expect(url).to.equal(`${server.url}/302`)
})
w.webContents.on('did-stop-loading', () => {
expect(w.webContents.getURL()).to.equal(
`${server.url}/navigate-302`,
'url should not have changed after navigation event'
)
done()
})
w.webContents.on('will-redirect', (e, url) => {
expect(url).to.equal(`${server.url}/200`)
})
w.loadURL(`${server.url}/navigate-302`)
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.show()', () => {
before(function () {
if (isCI) {
this.skip()
}
})
2017-11-01 14:48:09 +00:00
it('should focus on window', () => {
2016-03-25 20:03:49 +00:00
w.show()
assert(w.isFocused())
})
2017-11-01 14:48:09 +00:00
it('should make the window visible', () => {
2016-03-25 20:03:49 +00:00
w.show()
assert(w.isVisible())
})
2017-11-01 14:48:09 +00:00
it('emits when window is shown', (done) => {
w.once('show', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isVisible(), true)
2016-03-25 20:03:49 +00:00
done()
})
w.show()
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.hide()', () => {
before(function () {
if (isCI) {
this.skip()
}
})
2017-11-01 14:48:09 +00:00
it('should defocus on window', () => {
2016-03-25 20:03:49 +00:00
w.hide()
assert(!w.isFocused())
})
2017-11-01 14:48:09 +00:00
it('should make the window not visible', () => {
2016-03-25 20:03:49 +00:00
w.show()
w.hide()
assert(!w.isVisible())
})
2017-11-01 14:48:09 +00:00
it('emits when window is hidden', (done) => {
2016-03-25 20:03:49 +00:00
w.show()
2017-11-01 14:48:09 +00:00
w.once('hide', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isVisible(), false)
2016-03-25 20:03:49 +00:00
done()
})
w.hide()
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.showInactive()', () => {
it('should not focus on window', () => {
2016-03-25 20:03:49 +00:00
w.showInactive()
assert(!w.isFocused())
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.focus()', () => {
it('does not make the window become visible', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isVisible(), false)
2016-03-25 20:03:49 +00:00
w.focus()
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isVisible(), false)
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.blur()', () => {
it('removes focus from window', () => {
2016-03-25 20:03:49 +00:00
w.blur()
assert(!w.isFocused())
})
})
describe('BrowserWindow.getFocusedWindow()', () => {
it('returns the opener window when dev tools window is focused', (done) => {
w.show()
w.webContents.once('devtools-focused', () => {
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(BrowserWindow.getFocusedWindow(), w)
done()
})
2018-09-13 16:10:51 +00:00
w.webContents.openDevTools({ mode: 'undocked' })
})
})
describe('BrowserWindow.moveTop()', () => {
it('should not steal focus', async () => {
const posDelta = 50
const wShownInactive = emittedOnce(w, 'show')
w.showInactive()
await wShownInactive
assert(!w.isFocused())
const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' })
const otherWindowShown = emittedOnce(otherWindow, 'show')
otherWindow.loadURL('data:text/html,<html><body background-color: rgba(255,255,255,0)></body></html>')
otherWindow.show()
await otherWindowShown
assert(otherWindow.isFocused())
w.moveTop()
const wPos = w.getPosition()
const wMoving = emittedOnce(w, 'move')
w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta)
await wMoving
assert(!w.isFocused())
assert(otherWindow.isFocused())
const wFocused = emittedOnce(w, 'focus')
w.focus()
await wFocused
assert(w.isFocused())
otherWindow.moveTop()
const otherWindowPos = otherWindow.getPosition()
const otherWindowMoving = emittedOnce(otherWindow, 'move')
otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta)
await otherWindowMoving
assert(!otherWindow.isFocused())
assert(w.isFocused())
await closeWindow(otherWindow, { assertSingleWindow: false }).then(() => {
assert.strictEqual(BrowserWindow.getAllWindows().length, 2) // Test window + w
})
})
})
describe('BrowserWindow.capturePage(rect)', (done) => {
it('returns a Promise with a Buffer', async () => {
const image = await w.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
2016-03-25 20:03:49 +00:00
})
expect(image.isEmpty()).to.be.true()
2016-03-25 20:03:49 +00:00
})
// TODO(codebytere): remove when promisification is complete
it('returns a Promise with a Buffer (callback)', (done) => {
w.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
}, (image) => {
expect(image.isEmpty()).to.be.true()
done()
})
})
it('preserves transparency', async () => {
const w = await openTheWindow({
show: false,
width: 400,
height: 400,
transparent: true
})
const p = emittedOnce(w, 'ready-to-show')
w.loadURL('data:text/html,<html><body background-color: rgba(255,255,255,0)></body></html>')
await p
w.show()
const image = await w.capturePage()
const imgBuffer = image.toPNG()
// Check the 25th byte in the PNG.
// Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
expect(imgBuffer[25]).to.equal(6)
})
// TODO(codebytere): remove when promisification is complete
it('preserves transparency (callback)', (done) => {
openTheWindow({
show: false,
width: 400,
height: 400,
transparent: true
}).then(w => {
const p = emittedOnce(w, 'ready-to-show')
w.loadURL('data:text/html,<html><body background-color: rgba(255,255,255,0)></body></html>')
p.then(() => {
w.show()
w.capturePage((image) => {
const imgBuffer = image.toPNG()
// Check the 25th byte in the PNG.
// Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
expect(imgBuffer[25]).to.equal(6)
done()
})
})
})
})
2016-03-25 20:03:49 +00:00
})
describe('BrowserWindow.setBounds(bounds[, animate])', () => {
it('sets the window bounds with full bounds', () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 }
w.setBounds(fullBounds)
assertBoundsEqual(w.getBounds(), fullBounds)
})
it('sets the window bounds with partial bounds', () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 }
w.setBounds(fullBounds)
const boundsUpdate = { width: 200 }
w.setBounds(boundsUpdate)
const expectedBounds = Object.assign(fullBounds, boundsUpdate)
assertBoundsEqual(w.getBounds(), expectedBounds)
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.setSize(width, height)', () => {
it('sets the window size', async () => {
2017-11-01 14:48:09 +00:00
const size = [300, 400]
const resized = emittedOnce(w, 'resize')
2016-03-25 20:03:49 +00:00
w.setSize(size[0], size[1])
await resized
assertBoundsEqual(w.getSize(), size)
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => {
it('sets the maximum and minimum size of the window', () => {
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getMinimumSize(), [0, 0])
assert.deepStrictEqual(w.getMaximumSize(), [0, 0])
2016-07-12 17:19:34 +00:00
w.setMinimumSize(100, 100)
2016-09-08 20:46:55 +00:00
assertBoundsEqual(w.getMinimumSize(), [100, 100])
assertBoundsEqual(w.getMaximumSize(), [0, 0])
2016-07-12 17:19:34 +00:00
w.setMaximumSize(900, 600)
2016-09-08 20:46:55 +00:00
assertBoundsEqual(w.getMinimumSize(), [100, 100])
assertBoundsEqual(w.getMaximumSize(), [900, 600])
2016-07-12 17:19:34 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.setAspectRatio(ratio)', () => {
it('resets the behaviour when passing in 0', (done) => {
const size = [300, 400]
2016-06-29 16:37:10 +00:00
w.setAspectRatio(1 / 2)
w.setAspectRatio(0)
2017-11-01 14:48:09 +00:00
w.once('resize', () => {
2016-09-08 20:46:55 +00:00
assertBoundsEqual(w.getSize(), size)
done()
})
w.setSize(size[0], size[1])
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.setPosition(x, y)', () => {
it('sets the window position', (done) => {
const pos = [10, 10]
w.once('move', () => {
const newPos = w.getPosition()
2018-09-13 16:10:51 +00:00
assert.strictEqual(newPos[0], pos[0])
assert.strictEqual(newPos[1], pos[1])
2016-03-25 20:03:49 +00:00
done()
})
w.setPosition(pos[0], pos[1])
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.setContentSize(width, height)', () => {
it('sets the content size', () => {
const size = [400, 400]
2016-03-25 20:03:49 +00:00
w.setContentSize(size[0], size[1])
const after = w.getContentSize()
2018-09-13 16:10:51 +00:00
assert.strictEqual(after[0], size[0])
assert.strictEqual(after[1], size[1])
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('works for a frameless window', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
2016-01-12 02:40:23 +00:00
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
const size = [400, 400]
2016-03-25 20:03:49 +00:00
w.setContentSize(size[0], size[1])
2017-11-01 14:48:09 +00:00
const after = w.getContentSize()
2018-09-13 16:10:51 +00:00
assert.strictEqual(after[0], size[0])
assert.strictEqual(after[1], size[1])
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.setContentBounds(bounds)', () => {
it('sets the content size and position', (done) => {
2018-09-13 16:10:51 +00:00
const bounds = { x: 10, y: 10, width: 250, height: 250 }
2017-11-01 14:48:09 +00:00
w.once('resize', () => {
2016-09-08 20:46:55 +00:00
assertBoundsEqual(w.getContentBounds(), bounds)
done()
})
w.setContentBounds(bounds)
})
2017-11-01 14:48:09 +00:00
it('works for a frameless window', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300
})
2018-09-13 16:10:51 +00:00
const bounds = { x: 10, y: 10, width: 250, height: 250 }
2017-11-01 14:48:09 +00:00
w.once('resize', () => {
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getContentBounds(), bounds)
done()
})
w.setContentBounds(bounds)
2016-03-25 20:03:49 +00:00
})
})
describe(`BrowserWindow.getNormalBounds()`, () => {
describe(`Normal state`, () => {
it(`checks normal bounds after resize`, (done) => {
const size = [300, 400]
w.once('resize', () => {
assertBoundsEqual(w.getNormalBounds(), w.getBounds())
done()
})
w.setSize(size[0], size[1])
})
it(`checks normal bounds after move`, (done) => {
const pos = [10, 10]
w.once('move', () => {
assertBoundsEqual(w.getNormalBounds(), w.getBounds())
done()
})
w.setPosition(pos[0], pos[1])
})
})
describe(`Maximized state`, () => {
before(function () {
if (isCI) {
this.skip()
}
})
it(`checks normal bounds when maximized`, (done) => {
const bounds = w.getBounds()
w.once('maximize', () => {
assertBoundsEqual(w.getNormalBounds(), bounds)
done()
})
w.show()
w.maximize()
})
it(`checks normal bounds when unmaximized`, (done) => {
const bounds = w.getBounds()
w.once('maximize', () => {
w.unmaximize()
})
w.once('unmaximize', () => {
assertBoundsEqual(w.getNormalBounds(), bounds)
done()
})
w.show()
w.maximize()
})
})
describe(`Minimized state`, () => {
before(function () {
if (isCI) {
this.skip()
}
})
it(`checks normal bounds when minimized`, (done) => {
const bounds = w.getBounds()
w.once('minimize', () => {
assertBoundsEqual(w.getNormalBounds(), bounds)
done()
})
w.show()
w.minimize()
})
it(`checks normal bounds when restored`, (done) => {
const bounds = w.getBounds()
w.once('minimize', () => {
w.restore()
})
w.once('restore', () => {
assertBoundsEqual(w.getNormalBounds(), bounds)
done()
})
w.show()
w.minimize()
})
})
describe(`Fullscreen state`, () => {
before(function () {
if (isCI) {
this.skip()
}
if (process.platform === 'darwin') {
this.skip()
}
})
it(`checks normal bounds when fullscreen'ed`, (done) => {
const bounds = w.getBounds()
w.once('enter-full-screen', () => {
assertBoundsEqual(w.getNormalBounds(), bounds)
done()
})
w.show()
w.setFullScreen(true)
})
it(`checks normal bounds when unfullscreen'ed`, (done) => {
const bounds = w.getBounds()
w.once('enter-full-screen', () => {
w.setFullScreen(false)
})
w.once('leave-full-screen', () => {
assertBoundsEqual(w.getNormalBounds(), bounds)
done()
})
w.show()
w.setFullScreen(true)
})
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.setProgressBar(progress)', () => {
it('sets the progress', () => {
assert.doesNotThrow(() => {
if (process.platform === 'darwin') {
app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'))
}
2016-06-29 16:37:10 +00:00
w.setProgressBar(0.5)
2016-06-16 22:01:37 +00:00
if (process.platform === 'darwin') {
app.dock.setIcon(null)
}
w.setProgressBar(-1)
})
})
2017-11-01 14:48:09 +00:00
it('sets the progress using "paused" mode', () => {
assert.doesNotThrow(() => {
2018-09-13 16:10:51 +00:00
w.setProgressBar(0.5, { mode: 'paused' })
})
})
2017-11-01 14:48:09 +00:00
it('sets the progress using "error" mode', () => {
assert.doesNotThrow(() => {
2018-09-13 16:10:51 +00:00
w.setProgressBar(0.5, { mode: 'error' })
})
})
2017-11-01 14:48:09 +00:00
it('sets the progress using "normal" mode', () => {
assert.doesNotThrow(() => {
2018-09-13 16:10:51 +00:00
w.setProgressBar(0.5, { mode: 'normal' })
})
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
it('sets the window as always on top', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isAlwaysOnTop(), false)
w.setAlwaysOnTop(true, 'screen-saver')
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isAlwaysOnTop(), true)
w.setAlwaysOnTop(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isAlwaysOnTop(), false)
w.setAlwaysOnTop(true)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isAlwaysOnTop(), true)
})
it('raises an error when relativeLevel is out of bounds', function () {
if (process.platform !== 'darwin') {
// FIXME(alexeykuzmin): Skip the test instead of marking it as passed.
// afterEach hook won't be run if a test is skipped dynamically.
// If afterEach isn't run current window won't be destroyed
// and the next test will fail on assertion in `closeWindow()`.
// this.skip()
return
}
2017-11-01 14:48:09 +00:00
assert.throws(() => {
w.setAlwaysOnTop(true, '', -2147483644)
})
2017-11-01 14:48:09 +00:00
assert.throws(() => {
w.setAlwaysOnTop(true, '', 2147483632)
})
})
})
describe('BrowserWindow.alwaysOnTop() resets level on minimize', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
2017-11-01 14:48:09 +00:00
it('resets the windows level on minimize', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isAlwaysOnTop(), false)
w.setAlwaysOnTop(true, 'screen-saver')
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isAlwaysOnTop(), true)
w.minimize()
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isAlwaysOnTop(), false)
w.restore()
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isAlwaysOnTop(), true)
})
})
describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
describe('on macOS', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('allows changing cursor auto-hiding', () => {
assert.doesNotThrow(() => {
w.setAutoHideCursor(false)
w.setAutoHideCursor(true)
})
})
})
describe('on non-macOS platforms', () => {
before(function () {
if (process.platform === 'darwin') {
this.skip()
}
})
it('is not available', () => {
assert.ok(!w.setAutoHideCursor)
})
})
})
describe('BrowserWindow.selectPreviousTab()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', () => {
assert.doesNotThrow(() => {
w.selectPreviousTab()
})
})
})
describe('BrowserWindow.selectNextTab()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', () => {
assert.doesNotThrow(() => {
w.selectNextTab()
})
})
})
describe('BrowserWindow.mergeAllWindows()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', () => {
assert.doesNotThrow(() => {
w.mergeAllWindows()
})
})
})
describe('BrowserWindow.moveTabToNewWindow()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', () => {
assert.doesNotThrow(() => {
w.moveTabToNewWindow()
})
})
})
describe('BrowserWindow.toggleTabBar()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', () => {
assert.doesNotThrow(() => {
w.toggleTabBar()
})
})
})
describe('BrowserWindow.addTabbedWindow()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
2017-11-01 14:48:09 +00:00
it('does not throw', (done) => {
const tabbedWindow = new BrowserWindow({})
assert.doesNotThrow(() => {
w.addTabbedWindow(tabbedWindow)
})
2018-09-13 16:10:51 +00:00
assert.strictEqual(BrowserWindow.getAllWindows().length, 3) // Test window + w + tabbedWindow
2018-09-13 16:10:51 +00:00
closeWindow(tabbedWindow, { assertSingleWindow: false }).then(() => {
assert.strictEqual(BrowserWindow.getAllWindows().length, 2) // Test window + w
done()
})
})
2018-02-28 08:22:42 +00:00
it('throws when called on itself', () => {
assert.throws(() => {
w.addTabbedWindow(w)
}, /AddTabbedWindow cannot be called by a window on itself./)
})
})
describe('BrowserWindow.setWindowButtonVisibility()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', () => {
assert.doesNotThrow(() => {
w.setWindowButtonVisibility(true)
w.setWindowButtonVisibility(false)
})
})
it('throws with custom title bar buttons', () => {
assert.throws(() => {
w.destroy()
w = new BrowserWindow({
show: false,
titleBarStyle: 'customButtonsOnHover',
frame: false
})
w.setWindowButtonVisibility(true)
}, /Not supported for this window/)
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.setVibrancy(type)', () => {
it('allows setting, changing, and removing the vibrancy', () => {
assert.doesNotThrow(() => {
w.setVibrancy('light')
w.setVibrancy('dark')
w.setVibrancy(null)
w.setVibrancy('ultra-dark')
w.setVibrancy('')
})
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.setAppDetails(options)', () => {
before(function () {
if (process.platform !== 'win32') {
this.skip()
}
})
2016-11-28 22:30:43 +00:00
it('supports setting the app details', () => {
const iconPath = path.join(fixtures, 'assets', 'icon.ico')
2017-11-01 14:48:09 +00:00
assert.doesNotThrow(() => {
2018-09-13 16:10:51 +00:00
w.setAppDetails({ appId: 'my.app.id' })
w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 })
w.setAppDetails({ appIconPath: iconPath })
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' })
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' })
w.setAppDetails({ relaunchDisplayName: 'My app name' })
w.setAppDetails({
appId: 'my.app.id',
appIconPath: iconPath,
appIconIndex: 0,
relaunchCommand: 'my-app.exe arg1 arg2',
relaunchDisplayName: 'My app name'
})
w.setAppDetails({})
})
2016-11-28 22:30:43 +00:00
2017-11-01 14:48:09 +00:00
assert.throws(() => {
w.setAppDetails()
2016-11-28 22:30:43 +00:00
}, /Insufficient number of arguments\./)
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.fromId(id)', () => {
it('returns the window with id', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.id, BrowserWindow.fromId(w.id).id)
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.fromWebContents(webContents)', () => {
let contents = null
2017-11-01 14:48:09 +00:00
beforeEach(() => { contents = webContents.create({}) })
2017-11-01 14:48:09 +00:00
afterEach(() => { contents.destroy() })
2017-11-01 14:48:09 +00:00
it('returns the window with the webContents', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(BrowserWindow.fromWebContents(w.webContents).id, w.id)
assert.strictEqual(BrowserWindow.fromWebContents(contents), undefined)
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.fromDevToolsWebContents(webContents)', () => {
let contents = null
2017-11-01 14:48:09 +00:00
beforeEach(() => { contents = webContents.create({}) })
2017-11-01 14:48:09 +00:00
afterEach(() => { contents.destroy() })
2017-11-01 14:48:09 +00:00
it('returns the window with the webContents', (done) => {
w.webContents.once('devtools-opened', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(BrowserWindow.fromDevToolsWebContents(w.devToolsWebContents).id, w.id)
assert.strictEqual(BrowserWindow.fromDevToolsWebContents(w.webContents), undefined)
assert.strictEqual(BrowserWindow.fromDevToolsWebContents(contents), undefined)
done()
})
w.webContents.openDevTools()
})
})
describe('BrowserWindow.openDevTools()', () => {
it('does not crash for frameless window', () => {
w.destroy()
w = new BrowserWindow({ show: false })
w.openDevTools()
})
})
2017-11-22 22:37:46 +00:00
describe('BrowserWindow.fromBrowserView(browserView)', () => {
let bv = null
beforeEach(() => {
bv = new BrowserView()
w.setBrowserView(bv)
})
afterEach(() => {
w.setBrowserView(null)
bv.destroy()
})
it('returns the window with the browserView', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(BrowserWindow.fromBrowserView(bv).id, w.id)
2017-11-22 22:37:46 +00:00
})
it('returns undefined if not attached', () => {
w.setBrowserView(null)
assert.strictEqual(BrowserWindow.fromBrowserView(bv), null)
2017-11-22 22:37:46 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.setOpacity(opacity)', () => {
it('make window with initial opacity', () => {
2017-09-29 02:26:02 +00:00
w.destroy()
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
opacity: 0.5
})
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.getOpacity(), 0.5)
2017-09-29 02:26:02 +00:00
})
2017-11-01 14:48:09 +00:00
it('allows setting the opacity', () => {
assert.doesNotThrow(() => {
2017-09-29 02:26:02 +00:00
w.setOpacity(0.0)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.getOpacity(), 0.0)
2017-09-29 02:26:02 +00:00
w.setOpacity(0.5)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.getOpacity(), 0.5)
2017-09-29 02:26:02 +00:00
w.setOpacity(1.0)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.getOpacity(), 1.0)
2017-09-29 02:26:02 +00:00
})
})
})
describe('BrowserWindow.setShape(rects)', () => {
it('allows setting shape', () => {
assert.doesNotThrow(() => {
w.setShape([])
2018-09-13 16:10:51 +00:00
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }])
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }])
w.setShape([])
})
})
})
2017-11-01 14:48:09 +00:00
describe('"useContentSize" option', () => {
it('make window created with content size when used', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
2016-01-12 02:40:23 +00:00
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
useContentSize: true
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
const contentSize = w.getContentSize()
2018-09-13 16:10:51 +00:00
assert.strictEqual(contentSize[0], 400)
assert.strictEqual(contentSize[1], 400)
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('make window created with window size when not used', () => {
const size = w.getSize()
2018-09-13 16:10:51 +00:00
assert.strictEqual(size[0], 400)
assert.strictEqual(size[1], 400)
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('works for a frameless window', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
2016-01-12 02:40:23 +00:00
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400,
useContentSize: true
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
const contentSize = w.getContentSize()
2018-09-13 16:10:51 +00:00
assert.strictEqual(contentSize[0], 400)
assert.strictEqual(contentSize[1], 400)
2017-11-01 14:48:09 +00:00
const size = w.getSize()
2018-09-13 16:10:51 +00:00
assert.strictEqual(size[0], 400)
assert.strictEqual(size[1], 400)
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('"titleBarStyle" option', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
if (parseInt(os.release().split('.')[0]) < 14) {
this.skip()
}
})
2017-11-01 14:48:09 +00:00
it('creates browser window with hidden title bar', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
2016-01-12 02:40:23 +00:00
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden'
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
const contentSize = w.getContentSize()
2018-09-13 16:10:51 +00:00
assert.strictEqual(contentSize[1], 400)
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('creates browser window with hidden inset title bar', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
2016-01-12 02:40:23 +00:00
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hiddenInset'
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
const contentSize = w.getContentSize()
2018-09-13 16:10:51 +00:00
assert.strictEqual(contentSize[1], 400)
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('enableLargerThanScreen" option', () => {
before(function () {
if (process.platform === 'linux') {
this.skip()
}
})
2017-11-01 14:48:09 +00:00
beforeEach(() => {
2016-03-25 20:03:49 +00:00
w.destroy()
w = new BrowserWindow({
2016-01-12 02:40:23 +00:00
show: true,
width: 400,
height: 400,
enableLargerThanScreen: true
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
it('can move the window out of screen', () => {
2016-03-25 20:03:49 +00:00
w.setPosition(-10, -10)
2017-11-01 14:48:09 +00:00
const after = w.getPosition()
2018-09-13 16:10:51 +00:00
assert.strictEqual(after[0], -10)
assert.strictEqual(after[1], -10)
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('can set the window larger than screen', () => {
const size = screen.getPrimaryDisplay().size
2016-03-25 20:03:49 +00:00
size.width += 100
size.height += 100
w.setSize(size.width, size.height)
2016-09-08 20:46:55 +00:00
assertBoundsEqual(w.getSize(), [size.width, size.height])
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('"zoomToPageWidth" option', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
2016-10-27 18:54:27 +00:00
it('sets the window width to the page width when used', () => {
2016-10-27 18:54:27 +00:00
w.destroy()
w = new BrowserWindow({
show: false,
width: 500,
height: 400,
zoomToPageWidth: true
})
w.maximize()
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.getSize()[0], 500)
2016-10-27 18:54:27 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('"tabbingIdentifier" option', () => {
it('can be set on a window', () => {
2017-03-30 20:46:58 +00:00
w.destroy()
w = new BrowserWindow({
tabbingIdentifier: 'group1'
})
w.destroy()
w = new BrowserWindow({
tabbingIdentifier: 'group2',
frame: false
})
})
})
2017-11-01 14:48:09 +00:00
describe('"webPreferences" option', () => {
afterEach(() => { ipcMain.removeAllListeners('answer') })
2016-03-25 20:03:49 +00:00
2017-11-01 14:48:09 +00:00
describe('"preload" option', () => {
it('loads the script before other scripts in window', async () => {
2017-11-01 14:48:09 +00:00
const preload = path.join(fixtures, 'module', 'set-global.js')
2016-03-25 20:03:49 +00:00
w.destroy()
2016-01-12 02:40:23 +00:00
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload
}
2016-03-25 20:03:49 +00:00
})
const p = emittedOnce(ipcMain, 'answer')
w.loadFile(path.join(fixtures, 'api', 'preload.html'))
const [, test] = await p
expect(test).to.eql('preload')
2016-03-25 20:03:49 +00:00
})
it('can successfully delete the Buffer global', async () => {
2017-11-01 14:48:09 +00:00
const preload = path.join(fixtures, 'module', 'delete-buffer.js')
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload
}
})
const p = emittedOnce(ipcMain, 'answer')
w.loadFile(path.join(fixtures, 'api', 'preload.html'))
const [, test] = await p
expect(test.toString()).to.eql('buffer')
})
it('has synchronous access to all eventual window APIs', async () => {
const preload = path.join(fixtures, 'module', 'access-blink-apis.js')
const w = await openTheWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload
}
})
const p = emittedOnce(ipcMain, 'answer')
w.loadFile(path.join(fixtures, 'api', 'preload.html'))
const [, test] = await p
expect(test).to.be.an('object')
expect(test.atPreload).to.be.an('array')
expect(test.atLoad).to.be.an('array')
expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs')
})
2016-03-25 20:03:49 +00:00
})
2017-09-16 17:34:35 +00:00
describe('session preload scripts', function () {
const preloads = [
path.join(fixtures, 'module', 'set-global-preload-1.js'),
path.join(fixtures, 'module', 'set-global-preload-2.js')
]
const defaultSession = session.defaultSession
beforeEach(() => {
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(defaultSession.getPreloads(), [])
defaultSession.setPreloads(preloads)
})
afterEach(() => {
defaultSession.setPreloads([])
})
it('can set multiple session preload script', function () {
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(defaultSession.getPreloads(), preloads)
})
const generateSpecs = (description, sandbox) => {
describe(description, () => {
it('loads the script before other scripts in window including normal preloads', function (done) {
ipcMain.once('vars', function (event, preload1, preload2) {
assert.strictEqual(preload1, 'preload-1')
assert.strictEqual(preload2, 'preload-1-2')
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload: path.join(fixtures, 'module', 'get-global-preload.js')
}
})
w.loadURL('about:blank')
})
})
}
generateSpecs('without sandbox', false)
generateSpecs('with sandbox', true)
})
describe('"additionalArguments" option', () => {
it('adds extra args to process.argv in the renderer process', (done) => {
const preload = path.join(fixtures, 'module', 'check-arguments.js')
ipcMain.once('answer', (event, argv) => {
assert.ok(argv.includes('--my-magic-arg'))
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg']
}
})
w.loadFile(path.join(fixtures, 'api', 'blank.html'))
})
it('adds extra value args to process.argv in the renderer process', (done) => {
const preload = path.join(fixtures, 'module', 'check-arguments.js')
ipcMain.once('answer', (event, argv) => {
assert.ok(argv.includes('--my-magic-arg=foo'))
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg=foo']
}
})
w.loadFile(path.join(fixtures, 'api', 'blank.html'))
})
})
2017-11-01 14:48:09 +00:00
describe('"node-integration" option', () => {
it('disables node integration by default', (done) => {
2017-11-01 14:48:09 +00:00
const preload = path.join(fixtures, 'module', 'send-later.js')
ipcMain.once('answer', (event, typeofProcess, typeofBuffer) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(typeofProcess, 'undefined')
assert.strictEqual(typeofBuffer, 'undefined')
2016-03-25 20:03:49 +00:00
done()
})
w.destroy()
2016-01-12 02:40:23 +00:00
w = new BrowserWindow({
show: false,
webPreferences: {
preload
2016-01-12 02:40:23 +00:00
}
2016-03-25 20:03:49 +00:00
})
w.loadFile(path.join(fixtures, 'api', 'blank.html'))
2016-03-25 20:03:49 +00:00
})
})
2016-09-26 20:40:45 +00:00
describe('"enableRemoteModule" option', () => {
const generateSpecs = (description, sandbox) => {
describe(description, () => {
const preload = path.join(fixtures, 'module', 'preload-remote.js')
it('enables the remote module by default', async () => {
const w = await openTheWindow({
show: false,
webPreferences: {
preload,
sandbox
}
})
const p = emittedOnce(ipcMain, 'remote')
w.loadFile(path.join(fixtures, 'api', 'blank.html'))
const [, remote] = await p
expect(remote).to.equal('object')
})
it('disables the remote module when false', async () => {
const w = await openTheWindow({
show: false,
webPreferences: {
preload,
sandbox,
enableRemoteModule: false
}
})
const p = emittedOnce(ipcMain, 'remote')
w.loadFile(path.join(fixtures, 'api', 'blank.html'))
const [, remote] = await p
expect(remote).to.equal('undefined')
})
})
}
generateSpecs('without sandbox', false)
generateSpecs('with sandbox', true)
})
2017-11-01 14:48:09 +00:00
describe('"sandbox" option', () => {
2016-09-26 20:40:45 +00:00
function waitForEvents (emitter, events, callback) {
let count = events.length
for (const event of events) {
2016-09-26 20:40:45 +00:00
emitter.once(event, () => {
if (!--count) callback()
})
}
}
const preload = path.join(fixtures, 'module', 'preload-sandbox.js')
2017-11-01 14:48:09 +00:00
it('exposes ipcRenderer to preload script', (done) => {
2016-09-26 20:40:45 +00:00
ipcMain.once('answer', function (event, test) {
2018-09-13 16:10:51 +00:00
assert.strictEqual(test, 'preload')
2016-09-26 20:40:45 +00:00
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
2016-09-26 20:40:45 +00:00
sandbox: true,
preload
2016-09-26 20:40:45 +00:00
}
})
w.loadFile(path.join(fixtures, 'api', 'preload.html'))
2016-09-26 20:40:45 +00:00
})
it('exposes ipcRenderer to preload script (path has special chars)', function (done) {
const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js')
ipcMain.once('answer', function (event, test) {
2018-09-13 16:10:51 +00:00
assert.strictEqual(test, 'preload')
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
sandbox: true,
preload: preloadSpecialChars
}
})
w.loadFile(path.join(fixtures, 'api', 'preload.html'))
})
it('exposes "exit" event to preload script', function (done) {
2016-09-26 20:40:45 +00:00
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
2016-09-26 20:40:45 +00:00
sandbox: true,
preload
2016-09-26 20:40:45 +00:00
}
})
const htmlPath = path.join(fixtures, 'api', 'sandbox.html?exit-event')
2016-09-26 20:40:45 +00:00
const pageUrl = 'file://' + htmlPath
ipcMain.once('answer', function (event, url) {
let expectedUrl = pageUrl
if (process.platform === 'win32') {
expectedUrl = 'file:///' + htmlPath.replace(/\\/g, '/')
}
2018-09-13 16:10:51 +00:00
assert.strictEqual(url, expectedUrl)
2016-09-26 20:40:45 +00:00
done()
})
w.loadURL(pageUrl)
2016-09-26 20:40:45 +00:00
})
2017-11-01 14:48:09 +00:00
it('should open windows in same domain with cross-scripting enabled', (done) => {
2016-09-26 20:40:45 +00:00
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
2016-09-26 20:40:45 +00:00
sandbox: true,
preload
2016-09-26 20:40:45 +00:00
}
})
2017-07-11 00:12:40 +00:00
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
const htmlPath = path.join(fixtures, 'api', 'sandbox.html?window-open')
2016-09-26 20:40:45 +00:00
const pageUrl = 'file://' + htmlPath
w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
let expectedUrl = pageUrl
if (process.platform === 'win32') {
expectedUrl = 'file:///' + htmlPath.replace(/\\/g, '/')
}
2018-09-13 16:10:51 +00:00
assert.strictEqual(url, expectedUrl)
assert.strictEqual(frameName, 'popup!')
assert.strictEqual(options.width, 500)
assert.strictEqual(options.height, 600)
2016-09-26 20:40:45 +00:00
ipcMain.once('answer', function (event, html) {
2018-09-13 16:10:51 +00:00
assert.strictEqual(html, '<h1>scripting from opener</h1>')
2016-09-26 20:40:45 +00:00
done()
})
})
w.loadURL(pageUrl)
2016-09-26 20:40:45 +00:00
})
it('should open windows in another domain with cross-scripting disabled', async () => {
const w = await openTheWindow({
2016-09-26 20:40:45 +00:00
show: false,
webPreferences: {
sandbox: true,
preload
2016-09-26 20:40:45 +00:00
}
})
2017-07-11 00:12:40 +00:00
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
fix: use appropriate site instance for cross-site nav's (#15821) * fix: use Chromium's determined new site instance as candidate when navigating. When navigating to a new address, consider using Chromium's determined site instance for the new page as it should belong to an existing browsing instance when the navigation was triggered by window.open(). fixes 8100. * Revert "fix: use Chromium's determined new site instance as candidate when navigating." This reverts commit eb95f935654a2c4d4457821297670836c10fdfd5. * fix: delegate site instance creation back to content when sandboxed. * fix: ensure site isolation is on * test: adapt ut for cross-site navigation * fix: register pending processes during a navigation. * refactor: dont call loadURL for a window constructed from an existing webContents. * test: add sandboxed affinity UT's. * fix: check affinity before deciding if to force a new site instance. * chore: adapt subsequent patch. * refactor: constify logically const methods. * fix: do not reuse site instances when navigation redirects cross-site. * test: ensure localStorage accessible after x-site redirect. * test: adapt localStorage acess denied UT for site isolation. * fix: do not send render-view-deleted for speculative frames. * chore: amend tests after rebase. * test: add ut for webContents' render-view-deleted emission * fix: introduce current-render-view-deleted for current RVH's deletions. Revert render-view-deleted to being emitted with any RVH's deletion. current-render-view-deleted is emitted only when the RVH being deleted is the current one. * refactor: style and comments fixed.
2018-12-05 08:03:39 +00:00
const openerWindowOpen = emittedOnce(ipcMain, 'opener-loaded')
w.loadFile(
path.join(fixtures, 'api', 'sandbox.html'),
{ search: 'window-open-external' }
)
// Wait for a message from the main window saying that it's ready.
await openerWindowOpen
// Ask the opener to open a popup with window.opener.
const expectedPopupUrl = `${server.url}/cross-site` // Set in "sandbox.html".
const browserWindowCreated = emittedOnce(app, 'browser-window-created')
fix: use appropriate site instance for cross-site nav's (#15821) * fix: use Chromium's determined new site instance as candidate when navigating. When navigating to a new address, consider using Chromium's determined site instance for the new page as it should belong to an existing browsing instance when the navigation was triggered by window.open(). fixes 8100. * Revert "fix: use Chromium's determined new site instance as candidate when navigating." This reverts commit eb95f935654a2c4d4457821297670836c10fdfd5. * fix: delegate site instance creation back to content when sandboxed. * fix: ensure site isolation is on * test: adapt ut for cross-site navigation * fix: register pending processes during a navigation. * refactor: dont call loadURL for a window constructed from an existing webContents. * test: add sandboxed affinity UT's. * fix: check affinity before deciding if to force a new site instance. * chore: adapt subsequent patch. * refactor: constify logically const methods. * fix: do not reuse site instances when navigation redirects cross-site. * test: ensure localStorage accessible after x-site redirect. * test: adapt localStorage acess denied UT for site isolation. * fix: do not send render-view-deleted for speculative frames. * chore: amend tests after rebase. * test: add ut for webContents' render-view-deleted emission * fix: introduce current-render-view-deleted for current RVH's deletions. Revert render-view-deleted to being emitted with any RVH's deletion. current-render-view-deleted is emitted only when the RVH being deleted is the current one. * refactor: style and comments fixed.
2018-12-05 08:03:39 +00:00
w.webContents.send('open-the-popup', expectedPopupUrl)
// The page is going to open a popup that it won't be able to close.
// We have to close it from here later.
// XXX(alexeykuzmin): It will leak if the test fails too soon.
const [, popupWindow] = await browserWindowCreated
fix: use appropriate site instance for cross-site nav's (#15821) * fix: use Chromium's determined new site instance as candidate when navigating. When navigating to a new address, consider using Chromium's determined site instance for the new page as it should belong to an existing browsing instance when the navigation was triggered by window.open(). fixes 8100. * Revert "fix: use Chromium's determined new site instance as candidate when navigating." This reverts commit eb95f935654a2c4d4457821297670836c10fdfd5. * fix: delegate site instance creation back to content when sandboxed. * fix: ensure site isolation is on * test: adapt ut for cross-site navigation * fix: register pending processes during a navigation. * refactor: dont call loadURL for a window constructed from an existing webContents. * test: add sandboxed affinity UT's. * fix: check affinity before deciding if to force a new site instance. * chore: adapt subsequent patch. * refactor: constify logically const methods. * fix: do not reuse site instances when navigation redirects cross-site. * test: ensure localStorage accessible after x-site redirect. * test: adapt localStorage acess denied UT for site isolation. * fix: do not send render-view-deleted for speculative frames. * chore: amend tests after rebase. * test: add ut for webContents' render-view-deleted emission * fix: introduce current-render-view-deleted for current RVH's deletions. Revert render-view-deleted to being emitted with any RVH's deletion. current-render-view-deleted is emitted only when the RVH being deleted is the current one. * refactor: style and comments fixed.
2018-12-05 08:03:39 +00:00
// Ask the popup window for details.
const detailsAnswer = emittedOnce(ipcMain, 'child-loaded')
popupWindow.webContents.send('provide-details')
const [, openerIsNull, , locationHref] = await detailsAnswer
expect(openerIsNull).to.be.false('window.opener is null')
expect(locationHref).to.equal(expectedPopupUrl)
// Ask the page to access the popup.
fix: use appropriate site instance for cross-site nav's (#15821) * fix: use Chromium's determined new site instance as candidate when navigating. When navigating to a new address, consider using Chromium's determined site instance for the new page as it should belong to an existing browsing instance when the navigation was triggered by window.open(). fixes 8100. * Revert "fix: use Chromium's determined new site instance as candidate when navigating." This reverts commit eb95f935654a2c4d4457821297670836c10fdfd5. * fix: delegate site instance creation back to content when sandboxed. * fix: ensure site isolation is on * test: adapt ut for cross-site navigation * fix: register pending processes during a navigation. * refactor: dont call loadURL for a window constructed from an existing webContents. * test: add sandboxed affinity UT's. * fix: check affinity before deciding if to force a new site instance. * chore: adapt subsequent patch. * refactor: constify logically const methods. * fix: do not reuse site instances when navigation redirects cross-site. * test: ensure localStorage accessible after x-site redirect. * test: adapt localStorage acess denied UT for site isolation. * fix: do not send render-view-deleted for speculative frames. * chore: amend tests after rebase. * test: add ut for webContents' render-view-deleted emission * fix: introduce current-render-view-deleted for current RVH's deletions. Revert render-view-deleted to being emitted with any RVH's deletion. current-render-view-deleted is emitted only when the RVH being deleted is the current one. * refactor: style and comments fixed.
2018-12-05 08:03:39 +00:00
const touchPopupResult = emittedOnce(ipcMain, 'answer')
w.webContents.send('touch-the-popup')
fix: use appropriate site instance for cross-site nav's (#15821) * fix: use Chromium's determined new site instance as candidate when navigating. When navigating to a new address, consider using Chromium's determined site instance for the new page as it should belong to an existing browsing instance when the navigation was triggered by window.open(). fixes 8100. * Revert "fix: use Chromium's determined new site instance as candidate when navigating." This reverts commit eb95f935654a2c4d4457821297670836c10fdfd5. * fix: delegate site instance creation back to content when sandboxed. * fix: ensure site isolation is on * test: adapt ut for cross-site navigation * fix: register pending processes during a navigation. * refactor: dont call loadURL for a window constructed from an existing webContents. * test: add sandboxed affinity UT's. * fix: check affinity before deciding if to force a new site instance. * chore: adapt subsequent patch. * refactor: constify logically const methods. * fix: do not reuse site instances when navigation redirects cross-site. * test: ensure localStorage accessible after x-site redirect. * test: adapt localStorage acess denied UT for site isolation. * fix: do not send render-view-deleted for speculative frames. * chore: amend tests after rebase. * test: add ut for webContents' render-view-deleted emission * fix: introduce current-render-view-deleted for current RVH's deletions. Revert render-view-deleted to being emitted with any RVH's deletion. current-render-view-deleted is emitted only when the RVH being deleted is the current one. * refactor: style and comments fixed.
2018-12-05 08:03:39 +00:00
const [, popupAccessMessage] = await touchPopupResult
// Ask the popup to access the opener.
const touchOpenerResult = emittedOnce(ipcMain, 'answer')
popupWindow.webContents.send('touch-the-opener')
const [, openerAccessMessage] = await touchOpenerResult
// We don't need the popup anymore, and its parent page can't close it,
// so let's close it from here before we run any checks.
await closeWindow(popupWindow, { assertSingleWindow: false })
fix: use appropriate site instance for cross-site nav's (#15821) * fix: use Chromium's determined new site instance as candidate when navigating. When navigating to a new address, consider using Chromium's determined site instance for the new page as it should belong to an existing browsing instance when the navigation was triggered by window.open(). fixes 8100. * Revert "fix: use Chromium's determined new site instance as candidate when navigating." This reverts commit eb95f935654a2c4d4457821297670836c10fdfd5. * fix: delegate site instance creation back to content when sandboxed. * fix: ensure site isolation is on * test: adapt ut for cross-site navigation * fix: register pending processes during a navigation. * refactor: dont call loadURL for a window constructed from an existing webContents. * test: add sandboxed affinity UT's. * fix: check affinity before deciding if to force a new site instance. * chore: adapt subsequent patch. * refactor: constify logically const methods. * fix: do not reuse site instances when navigation redirects cross-site. * test: ensure localStorage accessible after x-site redirect. * test: adapt localStorage acess denied UT for site isolation. * fix: do not send render-view-deleted for speculative frames. * chore: amend tests after rebase. * test: add ut for webContents' render-view-deleted emission * fix: introduce current-render-view-deleted for current RVH's deletions. Revert render-view-deleted to being emitted with any RVH's deletion. current-render-view-deleted is emitted only when the RVH being deleted is the current one. * refactor: style and comments fixed.
2018-12-05 08:03:39 +00:00
expect(popupAccessMessage).to.be.a('string',
`child's .document is accessible from its parent window`)
fix: use appropriate site instance for cross-site nav's (#15821) * fix: use Chromium's determined new site instance as candidate when navigating. When navigating to a new address, consider using Chromium's determined site instance for the new page as it should belong to an existing browsing instance when the navigation was triggered by window.open(). fixes 8100. * Revert "fix: use Chromium's determined new site instance as candidate when navigating." This reverts commit eb95f935654a2c4d4457821297670836c10fdfd5. * fix: delegate site instance creation back to content when sandboxed. * fix: ensure site isolation is on * test: adapt ut for cross-site navigation * fix: register pending processes during a navigation. * refactor: dont call loadURL for a window constructed from an existing webContents. * test: add sandboxed affinity UT's. * fix: check affinity before deciding if to force a new site instance. * chore: adapt subsequent patch. * refactor: constify logically const methods. * fix: do not reuse site instances when navigation redirects cross-site. * test: ensure localStorage accessible after x-site redirect. * test: adapt localStorage acess denied UT for site isolation. * fix: do not send render-view-deleted for speculative frames. * chore: amend tests after rebase. * test: add ut for webContents' render-view-deleted emission * fix: introduce current-render-view-deleted for current RVH's deletions. Revert render-view-deleted to being emitted with any RVH's deletion. current-render-view-deleted is emitted only when the RVH being deleted is the current one. * refactor: style and comments fixed.
2018-12-05 08:03:39 +00:00
expect(popupAccessMessage).to.match(/^Blocked a frame with origin/)
expect(openerAccessMessage).to.be.a('string',
`opener .document is accessible from a popup window`)
expect(openerAccessMessage).to.match(/^Blocked a frame with origin/)
2016-09-26 20:40:45 +00:00
})
2017-11-01 14:48:09 +00:00
it('should inherit the sandbox setting in opened windows', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
})
const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js')
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preloadPath)
ipcMain.once('answer', (event, args) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(args.includes('--enable-sandbox'), true)
done()
})
w.loadFile(path.join(fixtures, 'api', 'new-window.html'))
})
2017-11-01 14:48:09 +00:00
it('should open windows with the options configured via new-window event listeners', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
})
const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js')
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preloadPath)
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'foo', 'bar')
ipcMain.once('answer', (event, args, webPreferences) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(webPreferences.foo, 'bar')
done()
})
w.loadFile(path.join(fixtures, 'api', 'new-window.html'))
})
2017-11-01 14:48:09 +00:00
it('should set ipc event sender correctly', (done) => {
2016-09-26 20:40:45 +00:00
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
2016-09-26 20:40:45 +00:00
}
})
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
let childWc
2016-09-26 20:40:45 +00:00
w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
childWc = options.webContents
2018-09-13 16:10:51 +00:00
assert.notStrictEqual(w.webContents, childWc)
2016-09-26 20:40:45 +00:00
})
ipcMain.once('parent-ready', function (event) {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.webContents, event.sender)
event.sender.send('verified')
})
ipcMain.once('child-ready', function (event) {
assert(childWc)
2018-09-13 16:10:51 +00:00
assert.strictEqual(childWc, event.sender)
event.sender.send('verified')
})
waitForEvents(ipcMain, [
'parent-answer',
'child-answer'
], done)
2018-09-13 16:10:51 +00:00
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'verify-ipc-sender' })
2016-09-26 20:40:45 +00:00
})
2017-11-01 14:48:09 +00:00
describe('event handling', () => {
it('works for window events', (done) => {
2016-09-26 20:40:45 +00:00
waitForEvents(w, [
'page-title-updated'
], done)
2018-09-13 16:10:51 +00:00
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'window-events' })
2016-09-26 20:40:45 +00:00
})
2017-11-01 14:48:09 +00:00
it('works for stop events', (done) => {
2016-09-26 20:40:45 +00:00
waitForEvents(w.webContents, [
'did-navigate',
'did-fail-load',
'did-stop-loading'
], done)
2018-09-13 16:10:51 +00:00
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'webcontents-stop' })
})
2017-11-01 14:48:09 +00:00
it('works for web contents events', (done) => {
2016-09-26 20:40:45 +00:00
waitForEvents(w.webContents, [
'did-finish-load',
'did-frame-finish-load',
'did-navigate-in-page',
'will-navigate',
'did-start-loading',
'did-stop-loading',
'did-frame-finish-load',
'dom-ready'
], done)
2018-09-13 16:10:51 +00:00
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'webcontents-events' })
2016-09-26 20:40:45 +00:00
})
})
it('supports calling preventDefault on new-window events', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
2017-01-12 18:28:02 +00:00
sandbox: true
}
})
const initialWebContents = webContents.getAllWebContents().map((i) => i.id)
ipcRenderer.send('prevent-next-new-window', w.webContents.id)
w.webContents.once('new-window', () => {
2017-05-02 18:14:52 +00:00
// We need to give it some time so the windows get properly disposed (at least on OSX).
setTimeout(() => {
const currentWebContents = webContents.getAllWebContents().map((i) => i.id)
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(currentWebContents, initialWebContents)
2017-05-02 18:14:52 +00:00
done()
2017-05-02 18:23:13 +00:00
}, 100)
})
w.loadFile(path.join(fixtures, 'pages', 'window-open.html'))
})
// TODO(alexeykuzmin): `GetProcessMemoryInfo()` is not available starting Ch67.
xit('releases memory after popup is closed', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload,
sandbox: true
}
})
2018-09-13 16:10:51 +00:00
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'allocate-memory' })
ipcMain.once('answer', function (event, { bytesBeforeOpen, bytesAfterOpen, bytesAfterClose }) {
const memoryIncreaseByOpen = bytesAfterOpen - bytesBeforeOpen
const memoryDecreaseByClose = bytesAfterOpen - bytesAfterClose
// decreased memory should be less than increased due to factors we
// can't control, but given the amount of memory allocated in the
// fixture, we can reasonably expect decrease to be at least 70% of
// increase
assert(memoryDecreaseByClose > memoryIncreaseByOpen * 0.7)
done()
})
})
2017-05-15 12:17:07 +00:00
// see #9387
it('properly manages remote object references after page reload', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload,
2017-05-15 12:17:07 +00:00
sandbox: true
}
})
2018-09-13 16:10:51 +00:00
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'reload-remote' })
2017-05-15 12:17:07 +00:00
ipcMain.on('get-remote-module-path', (event) => {
event.returnValue = path.join(fixtures, 'module', 'hello.js')
})
let reload = false
ipcMain.on('reloaded', (event) => {
event.returnValue = reload
reload = !reload
})
ipcMain.once('reload', (event) => {
event.sender.reload()
})
ipcMain.once('answer', (event, arg) => {
ipcMain.removeAllListeners('reloaded')
ipcMain.removeAllListeners('get-remote-module-path')
2018-09-13 16:10:51 +00:00
assert.strictEqual(arg, 'hi')
2017-05-15 12:17:07 +00:00
done()
})
})
it('properly manages remote object references after page reload in child window', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload,
2017-05-15 12:17:07 +00:00
sandbox: true
}
})
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
2018-09-13 16:10:51 +00:00
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'reload-remote-child' })
2017-05-15 12:17:07 +00:00
ipcMain.on('get-remote-module-path', (event) => {
event.returnValue = path.join(fixtures, 'module', 'hello-child.js')
})
let reload = false
ipcMain.on('reloaded', (event) => {
event.returnValue = reload
reload = !reload
})
ipcMain.once('reload', (event) => {
event.sender.reload()
})
ipcMain.once('answer', (event, arg) => {
ipcMain.removeAllListeners('reloaded')
ipcMain.removeAllListeners('get-remote-module-path')
2018-09-13 16:10:51 +00:00
assert.strictEqual(arg, 'hi child window')
2017-05-15 12:17:07 +00:00
done()
})
})
2018-03-14 03:01:40 +00:00
it('validates process APIs access in sandboxed renderer', (done) => {
2018-03-14 03:01:40 +00:00
ipcMain.once('answer', function (event, test) {
expect(test.hasCrash).to.be.true()
expect(test.hasHang).to.be.true()
expect(test.heapStatistics).to.be.an('object')
expect(test.processMemoryInfo).to.be.an('object')
expect(test.systemVersion).to.be.a('string')
expect(test.cpuUsage).to.be.an('object')
expect(test.ioCounters).to.be.an('object')
expect(test.arch).to.equal(remote.process.arch)
expect(test.platform).to.equal(remote.process.platform)
expect(test.env).to.deep.equal(remote.process.env)
expect(test.execPath).to.equal(remote.process.helperExecPath)
expect(test.sandboxed).to.be.true()
expect(test.type).to.equal('renderer')
expect(test.version).to.equal(remote.process.version)
expect(test.versions).to.deep.equal(remote.process.versions)
if (process.platform === 'linux' && test.osSandbox) {
expect(test.creationTime).to.be.null()
expect(test.systemMemoryInfo).to.be.null()
} else {
expect(test.creationTime).to.be.a('number')
expect(test.systemMemoryInfo).to.be.an('object')
}
2018-03-14 03:01:40 +00:00
done()
})
remote.process.env.sandboxmain = 'foo'
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
2018-03-14 03:01:40 +00:00
}
})
w.webContents.once('preload-error', (event, preloadPath, error) => {
done(error)
})
w.loadFile(path.join(fixtures, 'api', 'preload.html'))
2018-03-14 03:01:40 +00:00
})
it('webview in sandbox renderer', async () => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
webviewTag: true
}
})
const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview')
const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready')
w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'))
const [, webContents] = await didAttachWebview
const [, id] = await webviewDomReady
expect(webContents.id).to.equal(id)
})
2016-09-26 20:40:45 +00:00
})
2017-03-19 09:11:20 +00:00
2017-03-19 11:10:25 +00:00
describe('nativeWindowOpen option', () => {
2017-04-04 10:05:13 +00:00
beforeEach(() => {
2017-03-19 09:11:20 +00:00
w.destroy()
w = new BrowserWindow({
2017-04-06 02:44:20 +00:00
show: false,
2017-03-19 09:11:20 +00:00
webPreferences: {
nodeIntegration: true,
2017-03-19 09:11:20 +00:00
nativeWindowOpen: true
}
})
2017-04-04 10:05:13 +00:00
})
2017-04-18 15:11:23 +00:00
2017-04-04 10:05:13 +00:00
it('opens window of about:blank with cross-scripting enabled', (done) => {
2017-04-06 02:43:57 +00:00
ipcMain.once('answer', (event, content) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(content, 'Hello')
2017-04-04 10:05:13 +00:00
done()
})
w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'))
2017-04-04 10:05:13 +00:00
})
it('opens window of same domain with cross-scripting enabled', (done) => {
2017-04-06 02:43:57 +00:00
ipcMain.once('answer', (event, content) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(content, 'Hello')
2017-04-04 10:05:13 +00:00
done()
})
w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'))
2017-03-19 09:11:20 +00:00
})
2017-05-24 20:07:50 +00:00
it('blocks accessing cross-origin frames', (done) => {
ipcMain.once('answer', (event, content) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(content, 'Blocked a frame with origin "file://" from accessing a cross-origin frame.')
2017-05-24 20:07:50 +00:00
done()
})
w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'))
2017-05-24 20:07:50 +00:00
})
it('opens window from <iframe> tags', (done) => {
ipcMain.once('answer', (event, content) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(content, 'Hello')
done()
})
w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'))
});
(nativeModulesEnabled ? it : it.skip)('loads native addons correctly after reload', (done) => {
ipcMain.once('answer', (event, content) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(content, 'function')
2017-04-06 02:43:57 +00:00
ipcMain.once('answer', (event, content) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(content, 'function')
done()
2017-04-06 02:43:57 +00:00
})
w.reload()
2017-04-06 02:43:57 +00:00
})
w.loadFile(path.join(fixtures, 'api', 'native-window-open-native-addon.html'))
})
2017-11-01 14:48:09 +00:00
it('should inherit the nativeWindowOpen setting in opened windows', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nativeWindowOpen: true
}
})
const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js')
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preloadPath)
ipcMain.once('answer', (event, args) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(args.includes('--native-window-open'), true)
done()
})
w.loadFile(path.join(fixtures, 'api', 'new-window.html'))
})
2017-11-01 14:48:09 +00:00
it('should open windows with the options configured via new-window event listeners', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nativeWindowOpen: true
}
})
const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js')
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preloadPath)
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'foo', 'bar')
ipcMain.once('answer', (event, args, webPreferences) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(webPreferences.foo, 'bar')
done()
})
w.loadFile(path.join(fixtures, 'api', 'new-window.html'))
})
2017-11-01 14:48:09 +00:00
it('retains the original web preferences when window.location is changed to a new origin', async () => {
await serveFileFromProtocol('foo', path.join(fixtures, 'api', 'window-open-location-change.html'))
await serveFileFromProtocol('bar', path.join(fixtures, 'api', 'window-open-location-final.html'))
w.destroy()
w = new BrowserWindow({
show: true,
webPreferences: {
nativeWindowOpen: true
}
})
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', path.join(fixtures, 'api', 'window-open-preload.js'))
const p = emittedOnce(ipcMain, 'answer')
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'))
const [, args, typeofProcess] = await p
expect(args).not.to.include('--node-integration')
expect(args).to.include('--native-window-open')
expect(typeofProcess).to.eql('undefined')
})
it('should have nodeIntegration disabled in child windows', async () => {
const p = emittedOnce(ipcMain, 'answer')
w.loadFile(path.join(fixtures, 'api', 'native-window-open-argv.html'))
const [, typeofProcess] = await p
expect(typeofProcess).to.eql('undefined')
})
2017-03-19 09:11:20 +00:00
})
describe('"disableHtmlFullscreenWindowResize" option', () => {
it('prevents window from resizing when set', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
disableHtmlFullscreenWindowResize: true
}
})
w.webContents.once('did-finish-load', () => {
const size = w.getSize()
w.webContents.once('enter-html-full-screen', () => {
const newSize = w.getSize()
expect(newSize).to.deep.equal(size)
done()
})
w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true)
})
w.loadURL('about:blank')
})
})
2016-03-25 20:03:49 +00:00
})
describe('nativeWindowOpen + contextIsolation options', () => {
beforeEach(() => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nativeWindowOpen: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
}
})
})
it('opens window with cross-scripting enabled from isolated context', (done) => {
ipcMain.once('answer', (event, content) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(content, 'Hello')
done()
})
w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'))
2016-09-26 20:40:45 +00:00
})
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
describe('beforeunload handler', () => {
it('returning undefined would not prevent close', (done) => {
w.once('closed', () => { done() })
w.loadFile(path.join(fixtures, 'api', 'close-beforeunload-undefined.html'))
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('returning false would prevent close', (done) => {
w.once('onbeforeunload', () => { done() })
w.loadFile(path.join(fixtures, 'api', 'close-beforeunload-false.html'))
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('returning empty string would prevent close', (done) => {
w.once('onbeforeunload', () => { done() })
w.loadFile(path.join(fixtures, 'api', 'close-beforeunload-empty-string.html'))
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('emits for each close attempt', (done) => {
let beforeUnloadCount = 0
w.on('onbeforeunload', () => {
beforeUnloadCount += 1
2017-04-25 23:14:34 +00:00
if (beforeUnloadCount < 3) {
w.close()
} else if (beforeUnloadCount === 3) {
done()
}
})
2017-11-01 14:48:09 +00:00
w.webContents.once('did-finish-load', () => { w.close() })
w.loadFile(path.join(fixtures, 'api', 'beforeunload-false-prevent3.html'))
2017-04-25 23:14:34 +00:00
})
2017-11-01 14:48:09 +00:00
it('emits for each reload attempt', (done) => {
let beforeUnloadCount = 0
w.on('onbeforeunload', () => {
beforeUnloadCount += 1
2017-04-25 23:14:34 +00:00
if (beforeUnloadCount < 3) {
w.reload()
} else if (beforeUnloadCount === 3) {
done()
}
})
2017-11-01 14:48:09 +00:00
w.webContents.once('did-finish-load', () => {
w.webContents.once('did-finish-load', () => {
2017-04-25 23:14:34 +00:00
assert.fail('Reload was not prevented')
})
w.reload()
})
w.loadFile(path.join(fixtures, 'api', 'beforeunload-false-prevent3.html'))
2017-04-25 23:14:34 +00:00
})
2017-11-01 14:48:09 +00:00
it('emits for each navigation attempt', (done) => {
let beforeUnloadCount = 0
w.on('onbeforeunload', () => {
beforeUnloadCount += 1
2017-04-25 23:14:34 +00:00
if (beforeUnloadCount < 3) {
w.loadURL('about:blank')
} else if (beforeUnloadCount === 3) {
done()
}
})
2017-11-01 14:48:09 +00:00
w.webContents.once('did-finish-load', () => {
w.webContents.once('did-finish-load', () => {
2017-04-25 23:14:34 +00:00
assert.fail('Navigation was not prevented')
})
w.loadURL('about:blank')
})
w.loadFile(path.join(fixtures, 'api', 'beforeunload-false-prevent3.html'))
2017-04-25 23:14:34 +00:00
})
2016-03-25 20:03:49 +00:00
})
// visibilitychange event is broken upstream, see crbug.com/920839
xdescribe('document.visibilityState/hidden', () => {
2017-11-01 14:48:09 +00:00
beforeEach(() => { w.destroy() })
function onVisibilityChange (callback) {
2017-11-01 14:48:09 +00:00
ipcMain.on('pong', (event, visibilityState, hidden) => {
if (event.sender.id === w.webContents.id) {
callback(visibilityState, hidden)
}
})
}
function onNextVisibilityChange (callback) {
2017-11-01 14:48:09 +00:00
ipcMain.once('pong', (event, visibilityState, hidden) => {
if (event.sender.id === w.webContents.id) {
callback(visibilityState, hidden)
}
})
}
2017-11-01 14:48:09 +00:00
afterEach(() => { ipcMain.removeAllListeners('pong') })
2017-11-01 14:48:09 +00:00
it('visibilityState is initially visible despite window being hidden', (done) => {
w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true
}
})
let readyToShow = false
2017-11-01 14:48:09 +00:00
w.once('ready-to-show', () => {
readyToShow = true
})
2017-11-01 14:48:09 +00:00
onNextVisibilityChange((visibilityState, hidden) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(readyToShow, false)
assert.strictEqual(visibilityState, 'visible')
assert.strictEqual(hidden, false)
done()
})
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'))
})
2017-11-01 14:48:09 +00:00
it('visibilityState changes when window is hidden', (done) => {
w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true
}
})
2017-11-01 14:48:09 +00:00
onNextVisibilityChange((visibilityState, hidden) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(visibilityState, 'visible')
assert.strictEqual(hidden, false)
2017-11-01 14:48:09 +00:00
onNextVisibilityChange((visibilityState, hidden) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(visibilityState, 'hidden')
assert.strictEqual(hidden, true)
done()
})
w.hide()
})
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'))
})
2017-11-01 14:48:09 +00:00
it('visibilityState changes when window is shown', (done) => {
w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true
}
})
2017-11-01 14:48:09 +00:00
onNextVisibilityChange((visibilityState, hidden) => {
onVisibilityChange((visibilityState, hidden) => {
if (!hidden) {
2018-09-13 16:10:51 +00:00
assert.strictEqual(visibilityState, 'visible')
done()
}
})
w.hide()
w.show()
})
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'))
})
it('visibilityState changes when window is shown inactive', function (done) {
if (isCI && process.platform === 'win32') {
// FIXME(alexeykuzmin): Skip the test instead of marking it as passed.
// afterEach hook won't be run if a test is skipped dynamically.
// If afterEach isn't run current window won't be destroyed
// and the next test will fail on assertion in `closeWindow()`.
// this.skip()
return done()
}
w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true
}
})
2017-11-01 14:48:09 +00:00
onNextVisibilityChange((visibilityState, hidden) => {
onVisibilityChange((visibilityState, hidden) => {
if (!hidden) {
2018-09-13 16:10:51 +00:00
assert.strictEqual(visibilityState, 'visible')
done()
}
})
w.hide()
w.showInactive()
})
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'))
})
it('visibilityState changes when window is minimized', function (done) {
if (isCI && process.platform === 'linux') {
// FIXME(alexeykuzmin): Skip the test instead of marking it as passed.
// afterEach hook won't be run if a test is skipped dynamically.
// If afterEach isn't run current window won't be destroyed
// and the next test will fail on assertion in `closeWindow()`.
// this.skip()
return done()
}
2017-06-06 23:58:28 +00:00
w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true
}
})
2017-11-01 14:48:09 +00:00
onNextVisibilityChange((visibilityState, hidden) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(visibilityState, 'visible')
assert.strictEqual(hidden, false)
2017-11-01 14:48:09 +00:00
onNextVisibilityChange((visibilityState, hidden) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(visibilityState, 'hidden')
assert.strictEqual(hidden, true)
done()
})
w.minimize()
})
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'))
})
2017-11-01 14:48:09 +00:00
it('visibilityState remains visible if backgroundThrottling is disabled', (done) => {
w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
backgroundThrottling: false,
nodeIntegration: true
}
})
2017-11-01 14:48:09 +00:00
onNextVisibilityChange((visibilityState, hidden) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(visibilityState, 'visible')
assert.strictEqual(hidden, false)
2017-11-01 14:48:09 +00:00
onNextVisibilityChange((visibilityState, hidden) => {
done(new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`))
})
})
w.once('show', () => {
w.once('hide', () => {
w.once('show', () => {
done()
})
w.show()
})
w.hide()
})
w.show()
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'))
})
})
2017-11-01 14:48:09 +00:00
describe('new-window event', () => {
before(function () {
if (isCI && process.platform === 'darwin') {
this.skip()
}
})
2017-11-01 14:48:09 +00:00
it('emits when window.open is called', (done) => {
w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures) => {
e.preventDefault()
2018-09-13 16:10:51 +00:00
assert.strictEqual(url, 'http://host/')
assert.strictEqual(frameName, 'host')
assert.strictEqual(additionalFeatures[0], 'this-is-not-a-standard-feature')
done()
})
w.loadFile(path.join(fixtures, 'pages', 'window-open.html'))
})
2017-11-01 14:48:09 +00:00
it('emits when window.open is called with no webPreferences', (done) => {
w.destroy()
w = new BrowserWindow({ show: false })
w.webContents.once('new-window', function (e, url, frameName, disposition, options, additionalFeatures) {
2016-03-25 20:03:49 +00:00
e.preventDefault()
2018-09-13 16:10:51 +00:00
assert.strictEqual(url, 'http://host/')
assert.strictEqual(frameName, 'host')
assert.strictEqual(additionalFeatures[0], 'this-is-not-a-standard-feature')
2016-03-25 20:03:49 +00:00
done()
})
w.loadFile(path.join(fixtures, 'pages', 'window-open.html'))
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('emits when link with target is called', (done) => {
w.webContents.once('new-window', (e, url, frameName) => {
2016-03-25 20:03:49 +00:00
e.preventDefault()
2018-09-13 16:10:51 +00:00
assert.strictEqual(url, 'http://host/')
assert.strictEqual(frameName, 'target')
2016-03-25 20:03:49 +00:00
done()
})
w.loadFile(path.join(fixtures, 'pages', 'target-name.html'))
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('maximize event', () => {
if (isCI) return
2017-11-01 14:48:09 +00:00
it('emits when window is maximized', (done) => {
w.once('maximize', () => { done() })
2016-03-25 20:03:49 +00:00
w.show()
w.maximize()
})
})
2017-11-01 14:48:09 +00:00
describe('unmaximize event', () => {
if (isCI) return
2017-11-01 14:48:09 +00:00
it('emits when window is unmaximized', (done) => {
w.once('unmaximize', () => { done() })
2016-03-25 20:03:49 +00:00
w.show()
w.maximize()
w.unmaximize()
})
})
2017-11-01 14:48:09 +00:00
describe('minimize event', () => {
2017-11-01 14:56:53 +00:00
if (isCI) return
2017-11-01 14:48:09 +00:00
it('emits when window is minimized', (done) => {
w.once('minimize', () => { done() })
2016-03-25 20:03:49 +00:00
w.show()
w.minimize()
})
})
2017-11-01 14:48:09 +00:00
describe('sheet-begin event', () => {
let sheet = null
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
2017-11-01 14:48:09 +00:00
afterEach(() => {
2018-09-13 16:10:51 +00:00
return closeWindow(sheet, { assertSingleWindow: false }).then(() => { sheet = null })
})
2017-11-01 14:48:09 +00:00
it('emits when window opens a sheet', (done) => {
w.show()
2017-11-01 14:48:09 +00:00
w.once('sheet-begin', () => {
sheet.close()
done()
})
sheet = new BrowserWindow({
modal: true,
parent: w
})
})
})
2017-11-01 14:48:09 +00:00
describe('sheet-end event', () => {
let sheet = null
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
2017-11-01 14:48:09 +00:00
afterEach(() => {
2018-09-13 16:10:51 +00:00
return closeWindow(sheet, { assertSingleWindow: false }).then(() => { sheet = null })
})
2017-11-01 14:48:09 +00:00
it('emits when window has closed a sheet', (done) => {
w.show()
sheet = new BrowserWindow({
modal: true,
parent: w
})
2017-11-01 14:48:09 +00:00
w.once('sheet-end', () => { done() })
sheet.close()
})
})
describe('beginFrameSubscription method', () => {
before(function () {
// FIXME These specs crash on Linux when run in a docker container
if (isCI && process.platform === 'linux') {
this.skip()
}
})
it('does not crash when callback returns nothing', (done) => {
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'))
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function (data) {
// Pending endFrameSubscription to next tick can reliably reproduce
// a crash which happens when nothing is returned in the callback.
setTimeout(() => {
w.webContents.endFrameSubscription()
done()
})
})
})
})
2017-11-01 14:48:09 +00:00
it('subscribes to frame updates', (done) => {
let called = false
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'))
2017-11-01 14:48:09 +00:00
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function (data) {
// This callback might be called twice.
if (called) return
called = true
2018-09-13 16:10:51 +00:00
assert.notStrictEqual(data.length, 0)
w.webContents.endFrameSubscription()
done()
})
})
})
2017-11-01 14:48:09 +00:00
it('subscribes to frame updates (only dirty rectangle)', (done) => {
let called = false
2018-09-24 23:14:03 +00:00
let gotInitialFullSizeFrame = false
const [contentWidth, contentHeight] = w.getContentSize()
w.webContents.on('did-finish-load', () => {
w.webContents.beginFrameSubscription(true, (data, rect) => {
if (data.length === 0) {
// Chromium sometimes sends a 0x0 frame at the beginning of the
// page load.
return
}
if (rect.height === contentHeight && rect.width === contentWidth &&
!gotInitialFullSizeFrame) {
// The initial frame is full-size, but we're looking for a call
// with just the dirty-rect. The next frame should be a smaller
// rect.
gotInitialFullSizeFrame = true
return
}
// This callback might be called twice.
if (called) return
2018-09-24 23:14:03 +00:00
// We asked for just the dirty rectangle, so we expect to receive a
// rect smaller than the full size.
// TODO(jeremy): this is failing on windows currently; investigate.
// assert(rect.width < contentWidth || rect.height < contentHeight)
called = true
2018-09-24 23:14:03 +00:00
expect(data.length).to.equal(rect.width * rect.height * 4)
w.webContents.endFrameSubscription()
done()
})
2016-03-25 20:03:49 +00:00
})
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'))
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('throws error when subscriber is not well defined', (done) => {
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'))
try {
w.webContents.beginFrameSubscription(true, true)
2016-06-29 16:37:10 +00:00
} catch (e) {
done()
}
})
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
describe('savePage method', () => {
2016-03-25 20:03:49 +00:00
const savePageDir = path.join(fixtures, 'save_page')
const savePageHtmlPath = path.join(savePageDir, 'save_page.html')
const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js')
const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css')
2017-11-01 14:48:09 +00:00
after(() => {
try {
2016-03-25 20:03:49 +00:00
fs.unlinkSync(savePageCssPath)
fs.unlinkSync(savePageJsPath)
fs.unlinkSync(savePageHtmlPath)
fs.rmdirSync(path.join(savePageDir, 'save_page_files'))
fs.rmdirSync(savePageDir)
} catch (e) {
2016-01-19 19:31:47 +00:00
// Ignore error
}
2016-03-25 20:03:49 +00:00
})
it('should save page to disk', async () => {
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'))
await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete')
assert(fs.existsSync(savePageHtmlPath))
assert(fs.existsSync(savePageJsPath))
assert(fs.existsSync(savePageCssPath))
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow options argument is optional', () => {
it('should create a window with default size (800x600)', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
w = new BrowserWindow()
2017-11-01 14:48:09 +00:00
const size = w.getSize()
2018-09-13 16:10:51 +00:00
assert.strictEqual(size[0], 800)
assert.strictEqual(size[1], 600)
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('window states', () => {
it('does not resize frameless windows when states change', () => {
w.destroy()
w = new BrowserWindow({
frame: false,
width: 300,
height: 200,
show: false
})
w.setMinimizable(false)
w.setMinimizable(true)
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getSize(), [300, 200])
w.setResizable(false)
w.setResizable(true)
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getSize(), [300, 200])
w.setMaximizable(false)
w.setMaximizable(true)
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getSize(), [300, 200])
w.setFullScreenable(false)
w.setFullScreenable(true)
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getSize(), [300, 200])
w.setClosable(false)
w.setClosable(true)
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getSize(), [300, 200])
})
2017-11-01 14:48:09 +00:00
describe('resizable state', () => {
it('can be changed with resizable option', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
2018-09-13 16:10:51 +00:00
w = new BrowserWindow({ show: false, resizable: false })
assert.strictEqual(w.isResizable(), false)
if (process.platform === 'darwin') {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMaximizable(), true)
}
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('can be changed with setResizable method', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isResizable(), true)
2016-03-25 20:03:49 +00:00
w.setResizable(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isResizable(), false)
2016-03-25 20:03:49 +00:00
w.setResizable(true)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isResizable(), true)
2016-03-25 20:03:49 +00:00
})
it('works for a frameless window', () => {
w.destroy()
2018-09-13 16:10:51 +00:00
w = new BrowserWindow({ show: false, frame: false })
assert.strictEqual(w.isResizable(), true)
if (process.platform === 'win32') {
w.destroy()
2018-09-13 16:10:51 +00:00
w = new BrowserWindow({ show: false, thickFrame: false })
assert.strictEqual(w.isResizable(), false)
}
})
if (process.platform === 'win32') {
it('works for a window smaller than 64x64', () => {
w.destroy()
w = new BrowserWindow({
show: false,
frame: false,
resizable: false,
transparent: true
})
w.setContentSize(60, 60)
assertBoundsEqual(w.getContentSize(), [60, 60])
w.setContentSize(30, 30)
assertBoundsEqual(w.getContentSize(), [30, 30])
w.setContentSize(10, 10)
assertBoundsEqual(w.getContentSize(), [10, 10])
})
}
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
describe('loading main frame state', () => {
it('is true when the main frame is loading', (done) => {
w.webContents.on('did-start-loading', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.webContents.isLoadingMainFrame(), true)
done()
})
w.webContents.loadURL(server.url)
})
2017-11-01 14:48:09 +00:00
it('is false when only a subframe is loading', (done) => {
w.webContents.once('did-finish-load', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.webContents.isLoadingMainFrame(), false)
2017-11-01 14:48:09 +00:00
w.webContents.on('did-start-loading', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.webContents.isLoadingMainFrame(), false)
done()
})
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${server.url}/page2'
document.body.appendChild(iframe)
`)
})
w.webContents.loadURL(server.url)
})
2017-11-01 14:48:09 +00:00
it('is true when navigating to pages from the same origin', (done) => {
w.webContents.once('did-finish-load', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.webContents.isLoadingMainFrame(), false)
2017-11-01 14:48:09 +00:00
w.webContents.on('did-start-loading', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.webContents.isLoadingMainFrame(), true)
done()
})
w.webContents.loadURL(`${server.url}/page2`)
})
w.webContents.loadURL(server.url)
})
})
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
describe('window states (excluding Linux)', () => {
// FIXME(alexeykuzmin): Skip the tests instead of using the `return` here.
// Why it cannot be done now:
// - `.skip()` called in the 'before' hook doesn't affect
// nested `describe`s.
// - `.skip()` called in the 'beforeEach' hook prevents 'afterEach'
// hook from being called.
2016-01-23 11:35:30 +00:00
// Not implemented on Linux.
if (process.platform === 'linux') {
return
}
2016-03-25 20:03:49 +00:00
2017-11-01 14:48:09 +00:00
describe('movable state', () => {
it('can be changed with movable option', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
2018-09-13 16:10:51 +00:00
w = new BrowserWindow({ show: false, movable: false })
assert.strictEqual(w.isMovable(), false)
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('can be changed with setMovable method', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMovable(), true)
2016-03-25 20:03:49 +00:00
w.setMovable(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMovable(), false)
2016-03-25 20:03:49 +00:00
w.setMovable(true)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMovable(), true)
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('minimizable state', () => {
it('can be changed with minimizable option', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
2018-09-13 16:10:51 +00:00
w = new BrowserWindow({ show: false, minimizable: false })
assert.strictEqual(w.isMinimizable(), false)
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('can be changed with setMinimizable method', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMinimizable(), true)
2016-03-25 20:03:49 +00:00
w.setMinimizable(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMinimizable(), false)
2016-03-25 20:03:49 +00:00
w.setMinimizable(true)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMinimizable(), true)
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('maximizable state', () => {
it('can be changed with maximizable option', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
2018-09-13 16:10:51 +00:00
w = new BrowserWindow({ show: false, maximizable: false })
assert.strictEqual(w.isMaximizable(), false)
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('can be changed with setMaximizable method', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMaximizable(), true)
2016-03-25 20:03:49 +00:00
w.setMaximizable(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMaximizable(), false)
2016-03-25 20:03:49 +00:00
w.setMaximizable(true)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMaximizable(), true)
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('is not affected when changing other states', () => {
2016-03-25 20:03:49 +00:00
w.setMaximizable(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMaximizable(), false)
2016-03-25 20:03:49 +00:00
w.setMinimizable(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMaximizable(), false)
2016-03-25 20:03:49 +00:00
w.setClosable(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMaximizable(), false)
2016-08-04 22:06:49 +00:00
w.setMaximizable(true)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMaximizable(), true)
2016-08-04 22:06:49 +00:00
w.setClosable(true)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMaximizable(), true)
2016-08-04 22:06:49 +00:00
w.setFullScreenable(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMaximizable(), true)
2017-11-23 19:58:37 +00:00
})
2017-11-23 20:24:50 +00:00
})
describe('maximizable state (Windows only)', () => {
// Only implemented on windows.
if (process.platform !== 'win32') return
2017-11-23 19:58:37 +00:00
it('is reset to its former state', () => {
w.setMaximizable(false)
2016-08-04 22:06:49 +00:00
w.setResizable(false)
w.setResizable(true)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isMaximizable(), false)
w.setMaximizable(true)
w.setResizable(false)
w.setResizable(true)
assert.strictEqual(w.isMaximizable(), true)
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('fullscreenable state', () => {
before(function () {
// Only implemented on macOS.
if (process.platform !== 'darwin') {
this.skip()
}
})
2016-03-25 20:03:49 +00:00
2017-11-01 14:48:09 +00:00
it('can be changed with fullscreenable option', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
2018-09-13 16:10:51 +00:00
w = new BrowserWindow({ show: false, fullscreenable: false })
assert.strictEqual(w.isFullScreenable(), false)
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('can be changed with setFullScreenable method', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isFullScreenable(), true)
2016-03-25 20:03:49 +00:00
w.setFullScreenable(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isFullScreenable(), false)
2016-03-25 20:03:49 +00:00
w.setFullScreenable(true)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isFullScreenable(), true)
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('kiosk state', () => {
before(function () {
// Only implemented on macOS.
if (process.platform !== 'darwin') {
this.skip()
}
})
2017-01-13 23:05:04 +00:00
2017-11-01 14:48:09 +00:00
it('can be changed with setKiosk method', (done) => {
2017-01-13 23:05:04 +00:00
w.destroy()
w = new BrowserWindow()
w.setKiosk(true)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isKiosk(), true)
w.once('enter-full-screen', () => {
w.setKiosk(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isKiosk(), false)
})
w.once('leave-full-screen', () => {
done()
})
2017-01-13 23:05:04 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('fullscreen state with resizable set', () => {
before(function () {
// Only implemented on macOS.
if (process.platform !== 'darwin') {
this.skip()
}
})
2017-11-01 14:48:09 +00:00
it('resizable flag should be set to true and restored', (done) => {
w.destroy()
w = new BrowserWindow({ resizable: false })
w.once('enter-full-screen', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isResizable(), true)
w.setFullScreen(false)
})
w.once('leave-full-screen', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isResizable(), false)
done()
})
w.setFullScreen(true)
})
})
describe('fullscreen state', () => {
before(function () {
// Only implemented on macOS.
if (process.platform !== 'darwin') {
this.skip()
}
})
2017-01-13 23:05:04 +00:00
2017-11-01 14:48:09 +00:00
it('can be changed with setFullScreen method', (done) => {
2017-01-13 23:05:04 +00:00
w.destroy()
w = new BrowserWindow()
w.once('enter-full-screen', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isFullScreen(), true)
w.setFullScreen(false)
2017-01-24 19:22:25 +00:00
})
w.once('leave-full-screen', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isFullScreen(), false)
done()
})
2017-01-13 23:05:04 +00:00
w.setFullScreen(true)
})
2017-11-01 14:48:09 +00:00
it('should not be changed by setKiosk method', (done) => {
2017-01-24 19:22:25 +00:00
w.destroy()
w = new BrowserWindow()
w.once('enter-full-screen', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isFullScreen(), true)
2017-01-24 19:22:25 +00:00
w.setKiosk(true)
w.setKiosk(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isFullScreen(), true)
2017-01-24 19:22:25 +00:00
w.setFullScreen(false)
})
w.once('leave-full-screen', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isFullScreen(), false)
2017-01-24 19:22:25 +00:00
done()
})
2017-01-13 23:05:04 +00:00
w.setFullScreen(true)
})
})
2017-11-01 14:48:09 +00:00
describe('closable state', () => {
it('can be changed with closable option', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
2018-09-13 16:10:51 +00:00
w = new BrowserWindow({ show: false, closable: false })
assert.strictEqual(w.isClosable(), false)
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('can be changed with setClosable method', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isClosable(), true)
2016-03-25 20:03:49 +00:00
w.setClosable(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isClosable(), false)
2016-03-25 20:03:49 +00:00
w.setClosable(true)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isClosable(), true)
2016-03-25 20:03:49 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('hasShadow state', () => {
2016-01-23 12:03:56 +00:00
// On Window there is no shadow by default and it can not be changed
// dynamically.
2017-11-01 14:48:09 +00:00
it('can be changed with hasShadow option', () => {
2016-03-25 20:03:49 +00:00
w.destroy()
const hasShadow = process.platform !== 'darwin'
2018-09-13 16:10:51 +00:00
w = new BrowserWindow({ show: false, hasShadow: hasShadow })
assert.strictEqual(w.hasShadow(), hasShadow)
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('can be changed with setHasShadow method', () => {
2016-03-29 00:16:08 +00:00
if (process.platform !== 'darwin') return
2016-03-25 20:03:49 +00:00
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.hasShadow(), true)
2016-03-25 20:03:49 +00:00
w.setHasShadow(false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.hasShadow(), false)
2016-03-25 20:03:49 +00:00
w.setHasShadow(true)
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.hasShadow(), true)
2016-03-25 20:03:49 +00:00
})
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.restore()', () => {
it('should restore the previous window size', () => {
if (w != null) w.destroy()
w = new BrowserWindow({
minWidth: 800,
width: 800
})
const initialSize = w.getSize()
w.minimize()
w.restore()
assertBoundsEqual(w.getSize(), initialSize)
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.unmaximize()', () => {
it('should restore the previous window position', () => {
if (w != null) w.destroy()
w = new BrowserWindow()
const initialPosition = w.getPosition()
w.maximize()
w.unmaximize()
assertBoundsEqual(w.getPosition(), initialPosition)
})
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.setFullScreen(false)', () => {
before(function () {
// only applicable to windows: https://github.com/electron/electron/issues/6036
if (process.platform !== 'win32') {
this.skip()
}
})
2017-11-01 14:48:09 +00:00
it('should restore a normal visible window from a fullscreen startup state', (done) => {
w.webContents.once('did-finish-load', () => {
// start fullscreen and hidden
w.setFullScreen(true)
2017-11-01 14:48:09 +00:00
w.once('show', () => { w.setFullScreen(false) })
w.once('leave-full-screen', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isVisible(), true)
assert.strictEqual(w.isFullScreen(), false)
done()
})
w.show()
})
w.loadURL('about:blank')
})
2017-11-01 14:48:09 +00:00
it('should keep window hidden if already in hidden state', (done) => {
w.webContents.once('did-finish-load', () => {
w.once('leave-full-screen', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isVisible(), false)
assert.strictEqual(w.isFullScreen(), false)
done()
})
w.setFullScreen(false)
})
w.loadURL('about:blank')
})
})
describe('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('exits HTML fullscreen when window leaves fullscreen', (done) => {
w.destroy()
w = new BrowserWindow()
w.webContents.once('did-finish-load', () => {
w.once('enter-full-screen', () => {
w.once('leave-html-full-screen', () => {
done()
})
w.setFullScreen(false)
})
w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true)
})
w.loadURL('about:blank')
})
})
2017-11-01 14:48:09 +00:00
describe('parent window', () => {
2016-06-17 07:57:18 +00:00
let c = null
2017-11-01 14:48:09 +00:00
beforeEach(() => {
2016-06-17 07:57:18 +00:00
if (c != null) c.destroy()
2018-09-13 16:10:51 +00:00
c = new BrowserWindow({ show: false, parent: w })
2016-06-17 07:57:18 +00:00
})
2017-11-01 14:48:09 +00:00
afterEach(() => {
2016-06-17 07:57:18 +00:00
if (c != null) c.destroy()
c = null
})
2017-11-01 14:48:09 +00:00
describe('parent option', () => {
it('sets parent window', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(c.getParentWindow(), w)
2016-06-19 03:06:08 +00:00
})
2017-11-01 14:48:09 +00:00
it('adds window to child windows of parent', () => {
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getChildWindows(), [c])
2016-06-19 03:06:08 +00:00
})
2017-11-01 14:48:09 +00:00
it('removes from child windows of parent when window is closed', (done) => {
2016-06-19 03:06:08 +00:00
c.once('closed', () => {
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getChildWindows(), [])
2016-06-19 03:06:08 +00:00
done()
})
c.close()
})
2017-11-01 14:48:09 +00:00
it('should not affect the show option', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(c.isVisible(), false)
assert.strictEqual(c.getParentWindow().isVisible(), false)
})
2016-06-19 03:06:08 +00:00
})
2017-11-01 14:48:09 +00:00
describe('win.setParentWindow(parent)', () => {
beforeEach(() => {
if (c != null) c.destroy()
2018-09-13 16:10:51 +00:00
c = new BrowserWindow({ show: false })
})
2017-11-01 14:48:09 +00:00
it('sets parent window', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.getParentWindow(), null)
assert.strictEqual(c.getParentWindow(), null)
2016-06-17 07:57:18 +00:00
c.setParentWindow(w)
2018-09-13 16:10:51 +00:00
assert.strictEqual(c.getParentWindow(), w)
2016-06-17 07:57:18 +00:00
c.setParentWindow(null)
2018-09-13 16:10:51 +00:00
assert.strictEqual(c.getParentWindow(), null)
2016-06-17 07:57:18 +00:00
})
2017-11-01 14:48:09 +00:00
it('adds window to child windows of parent', () => {
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getChildWindows(), [])
2016-06-17 07:57:18 +00:00
c.setParentWindow(w)
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getChildWindows(), [c])
2016-06-17 07:57:18 +00:00
c.setParentWindow(null)
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getChildWindows(), [])
2016-06-17 07:57:18 +00:00
})
2017-11-01 14:48:09 +00:00
it('removes from child windows of parent when window is closed', (done) => {
2016-06-17 07:57:18 +00:00
c.once('closed', () => {
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(w.getChildWindows(), [])
2016-06-17 07:57:18 +00:00
done()
})
c.setParentWindow(w)
c.close()
})
})
2017-11-01 14:48:09 +00:00
describe('modal option', () => {
before(function () {
// The isEnabled API is not reliable on macOS.
if (process.platform === 'darwin') {
this.skip()
}
})
2017-11-01 14:48:09 +00:00
beforeEach(() => {
if (c != null) c.destroy()
2018-09-13 16:10:51 +00:00
c = new BrowserWindow({ show: false, parent: w, modal: true })
})
2017-11-01 14:48:09 +00:00
it('disables parent window', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isEnabled(), true)
c.show()
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isEnabled(), false)
})
it('re-enables an enabled parent window when closed', (done) => {
c.once('closed', () => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isEnabled(), true)
done()
})
c.show()
c.close()
})
it('does not re-enable a disabled parent window when closed', (done) => {
c.once('closed', () => {
assert.strictEqual(w.isEnabled(), false)
done()
})
w.setEnabled(false)
c.show()
c.close()
})
2017-11-01 14:48:09 +00:00
it('disables parent window recursively', () => {
const c2 = new BrowserWindow({ show: false, parent: w, modal: true })
c.show()
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isEnabled(), false)
c2.show()
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isEnabled(), false)
c.destroy()
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isEnabled(), false)
c2.destroy()
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.isEnabled(), true)
})
})
2016-06-17 07:57:18 +00:00
})
2017-11-01 14:48:09 +00:00
describe('window.webContents.send(channel, args...)', () => {
it('throws an error when the channel is missing', () => {
assert.throws(() => {
2016-03-25 20:03:49 +00:00
w.webContents.send()
}, 'Missing required channel argument')
2017-11-01 14:48:09 +00:00
assert.throws(() => {
2016-03-25 20:03:49 +00:00
w.webContents.send(null)
}, 'Missing required channel argument')
})
})
describe('window.getNativeWindowHandle()', () => {
before(function () {
if (!nativeModulesEnabled) {
this.skip()
}
})
it('returns valid handle', () => {
// The module's source code is hosted at
// https://github.com/electron/node-is-valid-window
const isValidWindow = remote.require('is-valid-window')
assert.ok(isValidWindow(w.getNativeWindowHandle()))
})
})
2017-11-01 14:48:09 +00:00
describe('extensions and dev tools extensions', () => {
let showPanelTimeoutId
const showLastDevToolsPanel = () => {
2017-11-01 14:48:09 +00:00
w.webContents.once('devtools-opened', () => {
const show = () => {
if (w == null || w.isDestroyed()) return
2018-09-13 16:10:51 +00:00
const { devToolsWebContents } = w
if (devToolsWebContents == null || devToolsWebContents.isDestroyed()) {
return
}
2017-11-01 14:48:09 +00:00
const showLastPanel = () => {
2017-01-24 23:44:01 +00:00
const lastPanelId = UI.inspectorView._tabbedPane._tabs.peekLast().id
UI.inspectorView.showPanel(lastPanelId)
}
devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false, () => {
showPanelTimeoutId = setTimeout(show, 100)
})
}
showPanelTimeoutId = setTimeout(show, 100)
})
}
2016-05-17 21:59:33 +00:00
2017-11-01 14:48:09 +00:00
afterEach(() => {
clearTimeout(showPanelTimeoutId)
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.addDevToolsExtension', () => {
describe('for invalid extensions', () => {
it('throws errors for missing manifest.json files', () => {
const nonexistentExtensionPath = path.join(__dirname, 'does-not-exist')
expect(() => {
BrowserWindow.addDevToolsExtension(nonexistentExtensionPath)
}).to.throw(/ENOENT: no such file or directory/)
})
2016-05-17 21:59:33 +00:00
it('throws errors for invalid manifest.json files', () => {
const badManifestExtensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'bad-manifest')
expect(() => {
BrowserWindow.addDevToolsExtension(badManifestExtensionPath)
}).to.throw(/Unexpected token }/)
})
})
2016-05-17 21:59:33 +00:00
2018-07-05 01:33:45 +00:00
describe('for a valid extension', () => {
const extensionName = 'foo'
2016-05-17 21:59:33 +00:00
const removeExtension = () => {
BrowserWindow.removeDevToolsExtension('foo')
expect(BrowserWindow.getDevToolsExtensions().hasOwnProperty(extensionName)).to.equal(false)
}
2016-05-17 21:56:00 +00:00
const addExtension = () => {
const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo')
BrowserWindow.addDevToolsExtension(extensionPath)
expect(BrowserWindow.getDevToolsExtensions().hasOwnProperty(extensionName)).to.equal(true)
showLastDevToolsPanel()
w.loadURL('about:blank')
}
// After* hooks won't be called if a test fail.
// So let's make a clean-up in the before hook.
beforeEach(removeExtension)
describe('when the devtools is docked', () => {
beforeEach(function (done) {
addExtension()
2018-09-13 16:10:51 +00:00
w.webContents.openDevTools({ mode: 'bottom' })
ipcMain.once('answer', (event, message) => {
this.message = message
done()
})
})
describe('created extension info', function () {
it('has proper "runtimeId"', function () {
expect(this.message).to.have.own.property('runtimeId')
expect(this.message.runtimeId).to.equal(extensionName)
})
it('has "tabId" matching webContents id', function () {
expect(this.message).to.have.own.property('tabId')
expect(this.message.tabId).to.equal(w.webContents.id)
})
it('has "i18nString" with proper contents', function () {
expect(this.message).to.have.own.property('i18nString')
expect(this.message.i18nString).to.equal('foo - bar (baz)')
})
it('has "storageItems" with proper contents', function () {
expect(this.message).to.have.own.property('storageItems')
expect(this.message.storageItems).to.deep.equal({
local: {
2018-09-13 16:10:51 +00:00
set: { hello: 'world', world: 'hello' },
remove: { world: 'hello' },
clear: {}
},
sync: {
2018-09-13 16:10:51 +00:00
set: { foo: 'bar', bar: 'foo' },
remove: { foo: 'bar' },
clear: {}
}
})
})
2016-05-17 21:56:00 +00:00
})
2016-05-17 21:52:45 +00:00
})
describe('when the devtools is undocked', () => {
beforeEach(function (done) {
addExtension()
2018-09-13 16:10:51 +00:00
w.webContents.openDevTools({ mode: 'undocked' })
ipcMain.once('answer', (event, message, extensionId) => {
this.message = message
done()
})
})
2016-05-17 21:56:00 +00:00
describe('created extension info', function () {
it('has proper "runtimeId"', function () {
expect(this.message).to.have.own.property('runtimeId')
expect(this.message.runtimeId).to.equal(extensionName)
})
it('has "tabId" matching webContents id', function () {
expect(this.message).to.have.own.property('tabId')
expect(this.message.tabId).to.equal(w.webContents.id)
})
2016-05-17 21:56:00 +00:00
})
2016-05-17 21:52:45 +00:00
})
})
})
2018-07-05 01:33:45 +00:00
it('works when used with partitions', (done) => {
if (w != null) {
w.destroy()
}
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'temp'
}
})
const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo')
BrowserWindow.removeDevToolsExtension('foo')
BrowserWindow.addDevToolsExtension(extensionPath)
showLastDevToolsPanel()
ipcMain.once('answer', function (event, message) {
2018-09-13 16:10:51 +00:00
assert.strictEqual(message.runtimeId, 'foo')
done()
})
w.loadURL('about:blank')
w.webContents.openDevTools({ mode: 'bottom' })
})
2017-11-01 14:48:09 +00:00
it('serializes the registered extensions on quit', () => {
const extensionName = 'foo'
const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', extensionName)
const serializedPath = path.join(app.getPath('userData'), 'DevTools Extensions')
2016-03-25 20:03:49 +00:00
BrowserWindow.addDevToolsExtension(extensionPath)
app.emit('will-quit')
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(JSON.parse(fs.readFileSync(serializedPath)), [extensionPath])
2016-03-25 20:03:49 +00:00
BrowserWindow.removeDevToolsExtension(extensionName)
app.emit('will-quit')
2018-09-13 16:10:51 +00:00
assert.strictEqual(fs.existsSync(serializedPath), false)
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
describe('BrowserWindow.addExtension', () => {
beforeEach(() => {
BrowserWindow.removeExtension('foo')
2018-09-13 16:10:51 +00:00
assert.strictEqual(BrowserWindow.getExtensions().hasOwnProperty('foo'), false)
const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo')
BrowserWindow.addExtension(extensionPath)
2018-09-13 16:10:51 +00:00
assert.strictEqual(BrowserWindow.getExtensions().hasOwnProperty('foo'), true)
showLastDevToolsPanel()
w.loadURL('about:blank')
})
2017-11-01 14:48:09 +00:00
it('throws errors for missing manifest.json files', () => {
assert.throws(() => {
BrowserWindow.addExtension(path.join(__dirname, 'does-not-exist'))
}, /ENOENT: no such file or directory/)
})
2017-11-01 14:48:09 +00:00
it('throws errors for invalid manifest.json files', () => {
assert.throws(() => {
BrowserWindow.addExtension(path.join(__dirname, 'fixtures', 'devtools-extensions', 'bad-manifest'))
}, /Unexpected token }/)
})
})
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
describe('window.webContents.executeJavaScript', () => {
const expected = 'hello, world!'
const expectedErrorMsg = 'woops!'
const code = `(() => "${expected}")()`
const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`
const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`
2017-11-18 18:59:09 +00:00
const errorTypes = new Set([
Error,
ReferenceError,
EvalError,
RangeError,
SyntaxError,
TypeError,
URIError
])
2016-03-25 20:03:49 +00:00
2017-11-01 14:48:09 +00:00
it('doesnt throw when no calback is provided', () => {
2016-03-25 20:03:49 +00:00
const result = ipcRenderer.sendSync('executeJavaScript', code, false)
2018-09-13 16:10:51 +00:00
assert.strictEqual(result, 'success')
2016-03-25 20:03:49 +00:00
})
2017-11-01 14:48:09 +00:00
it('returns result when calback is provided', (done) => {
2016-03-25 20:03:49 +00:00
ipcRenderer.send('executeJavaScript', code, true)
ipcRenderer.once('executeJavaScript-response', function (event, result) {
2018-09-13 16:10:51 +00:00
assert.strictEqual(result, expected)
2016-03-25 20:03:49 +00:00
done()
})
})
2017-11-01 14:48:09 +00:00
it('returns result if the code returns an asyncronous promise', (done) => {
2016-10-10 23:40:05 +00:00
ipcRenderer.send('executeJavaScript', asyncCode, true)
2017-11-01 14:48:09 +00:00
ipcRenderer.once('executeJavaScript-response', (event, result) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(result, expected)
2016-10-10 23:40:05 +00:00
done()
})
})
2017-11-01 14:48:09 +00:00
it('resolves the returned promise with the result when a callback is specified', (done) => {
ipcRenderer.send('executeJavaScript', code, true)
2017-11-01 14:48:09 +00:00
ipcRenderer.once('executeJavaScript-promise-response', (event, result) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(result, expected)
done()
})
})
2017-11-01 14:48:09 +00:00
it('resolves the returned promise with the result when no callback is specified', (done) => {
2017-03-06 18:49:23 +00:00
ipcRenderer.send('executeJavaScript', code, false)
2017-11-01 14:48:09 +00:00
ipcRenderer.once('executeJavaScript-promise-response', (event, result) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(result, expected)
2017-03-06 18:49:23 +00:00
done()
})
})
2017-11-01 14:48:09 +00:00
it('resolves the returned promise with the result if the code returns an asyncronous promise', (done) => {
ipcRenderer.send('executeJavaScript', asyncCode, true)
2017-11-01 14:48:09 +00:00
ipcRenderer.once('executeJavaScript-promise-response', (event, result) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(result, expected)
done()
})
})
2017-11-01 14:48:09 +00:00
it('rejects the returned promise if an async error is thrown', (done) => {
ipcRenderer.send('executeJavaScript', badAsyncCode, true)
2017-11-01 14:48:09 +00:00
ipcRenderer.once('executeJavaScript-promise-error', (event, error) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(error, expectedErrorMsg)
done()
})
})
it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
2017-11-18 18:59:09 +00:00
for (const error in errorTypes) {
await new Promise((resolve) => {
2017-11-18 18:59:09 +00:00
ipcRenderer.send('executeJavaScript', `Promise.reject(new ${error.name}("Wamp-wamp")`, true)
ipcRenderer.once('executeJavaScript-promise-error-name', (event, name) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(name, error.name)
resolve()
})
})
}
})
2017-11-01 14:48:09 +00:00
it('works after page load and during subframe load', (done) => {
w.webContents.once('did-finish-load', () => {
// initiate a sub-frame load, then try and execute script during it
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${server.url}/slow'
document.body.appendChild(iframe)
2017-11-01 14:48:09 +00:00
`, () => {
w.webContents.executeJavaScript('console.log(\'hello\')', () => {
done()
})
})
})
w.loadURL(server.url)
})
2017-11-01 14:48:09 +00:00
it('executes after page load', (done) => {
w.webContents.executeJavaScript(code, (result) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(result, expected)
done()
})
w.loadURL(server.url)
})
2017-11-01 14:48:09 +00:00
it('works with result objects that have DOM class prototypes', (done) => {
w.webContents.executeJavaScript('document.location', (result) => {
2018-09-13 16:10:51 +00:00
assert.strictEqual(result.origin, server.url)
assert.strictEqual(result.protocol, 'http:')
done()
})
w.loadURL(server.url)
})
2016-03-25 20:03:49 +00:00
})
2016-07-31 15:10:53 +00:00
2017-11-01 14:48:09 +00:00
describe('previewFile', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('opens the path in Quick Look on macOS', () => {
2017-11-01 14:48:09 +00:00
assert.doesNotThrow(() => {
w.previewFile(__filename)
w.closeFilePreview()
})
})
})
describe('contextIsolation option with and without sandbox option', () => {
const expectedContextData = {
preloadContext: {
preloadProperty: 'number',
pageProperty: 'undefined',
typeofRequire: 'function',
typeofProcess: 'object',
typeofArrayPush: 'function',
typeofFunctionApply: 'function',
typeofPreloadExecuteJavaScriptProperty: 'undefined'
},
pageContext: {
preloadProperty: 'undefined',
pageProperty: 'string',
typeofRequire: 'undefined',
typeofProcess: 'undefined',
typeofArrayPush: 'number',
typeofFunctionApply: 'boolean',
typeofPreloadExecuteJavaScriptProperty: 'number',
typeofOpenedWindow: 'object'
}
}
2017-01-09 23:18:47 +00:00
beforeEach(() => {
if (iw != null) iw.destroy()
iw = new BrowserWindow({
2017-01-09 23:18:47 +00:00
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
})
if (ws != null) ws.destroy()
ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
})
})
afterEach(() => {
if (iw != null) iw.destroy()
if (ws != null) ws.destroy()
2017-01-09 23:18:47 +00:00
})
2016-12-13 19:47:54 +00:00
it('separates the page context from the Electron/preload context', async () => {
const p = emittedOnce(ipcMain, 'isolated-world')
iw.loadFile(path.join(fixtures, 'api', 'isolated.html'))
const [, data] = await p
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(data, expectedContextData)
})
it('recreates the contexts on reload', async () => {
await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'))
const isolatedWorld = emittedOnce(ipcMain, 'isolated-world')
iw.webContents.reload()
const [, data] = await isolatedWorld
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(data, expectedContextData)
})
it('enables context isolation on child windows', async () => {
const browserWindowCreated = emittedOnce(app, 'browser-window-created')
iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'))
const [, window] = await browserWindowCreated
assert.ok(window.webContents.getLastWebPreferences().contextIsolation)
})
it('separates the page context from the Electron/preload context with sandbox on', async () => {
const p = emittedOnce(ipcMain, 'isolated-world')
ws.loadFile(path.join(fixtures, 'api', 'isolated.html'))
const [, data] = await p
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(data, expectedContextData)
})
it('recreates the contexts on reload with sandbox on', async () => {
await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'))
const isolatedWorld = emittedOnce(ipcMain, 'isolated-world')
ws.webContents.reload()
const [, data] = await isolatedWorld
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(data, expectedContextData)
})
it('supports fetch api', async () => {
const fetchWindow = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
}
})
const p = emittedOnce(ipcMain, 'isolated-fetch-error')
fetchWindow.loadURL('about:blank')
const [, error] = await p
fetchWindow.destroy()
2018-09-13 16:10:51 +00:00
assert.strictEqual(error, 'Failed to fetch')
})
it('doesn\'t break ipc serialization', async () => {
const p = emittedOnce(ipcMain, 'isolated-world')
iw.loadURL('about:blank')
iw.webContents.executeJavaScript(`
const opened = window.open()
openedLocation = opened.location.href
opened.close()
window.postMessage({openedLocation}, '*')
`)
const [, data] = await p
2018-09-13 16:10:51 +00:00
assert.strictEqual(data.pageContext.openedLocation, '')
})
2016-12-13 19:47:54 +00:00
})
2017-11-01 14:48:09 +00:00
describe('offscreen rendering', () => {
beforeEach(function () {
if (!features.isOffscreenRenderingEnabled()) {
// XXX(alexeykuzmin): "afterEach" hook is not called
// for skipped tests, we have to close the window manually.
return closeTheWindow().then(() => { this.skip() })
}
if (w != null) w.destroy()
w = new BrowserWindow({
2017-05-13 00:14:30 +00:00
width: 100,
height: 100,
2016-07-31 15:10:53 +00:00
show: false,
webPreferences: {
backgroundThrottling: false,
offscreen: true
}
})
2016-08-03 01:27:55 +00:00
})
2017-11-01 14:48:09 +00:00
it('creates offscreen window with correct size', (done) => {
2017-05-13 00:14:30 +00:00
w.webContents.once('paint', function (event, rect, data) {
2018-09-13 16:10:51 +00:00
assert.notStrictEqual(data.length, 0)
const size = data.getSize()
const scale = process.platform === 'darwin' ? devicePixelRatio : 1
assertWithinDelta(size.width, 100 * scale, 2, 'width')
assertWithinDelta(size.height, 100 * scale, 2, 'height')
2016-07-31 15:10:53 +00:00
done()
})
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'))
2016-07-31 15:10:53 +00:00
})
2017-11-01 14:48:09 +00:00
describe('window.webContents.isOffscreen()', () => {
it('is true for offscreen type', () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'))
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.webContents.isOffscreen(), true)
2016-07-31 15:10:53 +00:00
})
2017-11-01 14:48:09 +00:00
it('is false for regular window', () => {
const c = new BrowserWindow({ show: false })
2018-09-13 16:10:51 +00:00
assert.strictEqual(c.webContents.isOffscreen(), false)
2016-08-03 01:27:55 +00:00
c.destroy()
2016-07-31 15:10:53 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('window.webContents.isPainting()', () => {
it('returns whether is currently painting', (done) => {
2017-05-13 00:14:30 +00:00
w.webContents.once('paint', function (event, rect, data) {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.webContents.isPainting(), true)
2016-07-31 15:10:53 +00:00
done()
})
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'))
2016-07-31 15:10:53 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('window.webContents.stopPainting()', () => {
it('stops painting', (done) => {
w.webContents.on('dom-ready', () => {
2016-08-03 01:27:55 +00:00
w.webContents.stopPainting()
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.webContents.isPainting(), false)
2016-07-31 15:10:53 +00:00
done()
})
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'))
2016-07-31 15:10:53 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('window.webContents.startPainting()', () => {
it('starts painting', (done) => {
w.webContents.on('dom-ready', () => {
2016-08-03 01:27:55 +00:00
w.webContents.stopPainting()
w.webContents.startPainting()
2017-05-13 00:14:30 +00:00
w.webContents.once('paint', function (event, rect, data) {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.webContents.isPainting(), true)
2016-07-31 15:10:53 +00:00
done()
})
})
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'))
2016-07-31 15:10:53 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('window.webContents.getFrameRate()', () => {
it('has default frame rate', (done) => {
2017-05-13 00:14:30 +00:00
w.webContents.once('paint', function (event, rect, data) {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.webContents.getFrameRate(), 60)
2016-07-31 15:10:53 +00:00
done()
})
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'))
2016-07-31 15:10:53 +00:00
})
})
2017-11-01 14:48:09 +00:00
describe('window.webContents.setFrameRate(frameRate)', () => {
it('sets custom frame rate', (done) => {
w.webContents.on('dom-ready', () => {
2016-08-03 01:27:55 +00:00
w.webContents.setFrameRate(30)
2017-05-13 00:14:30 +00:00
w.webContents.once('paint', function (event, rect, data) {
2018-09-13 16:10:51 +00:00
assert.strictEqual(w.webContents.getFrameRate(), 30)
2016-07-31 15:10:53 +00:00
done()
})
})
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'))
2016-07-31 15:10:53 +00:00
})
})
})
2016-03-25 20:03:49 +00:00
})
2016-09-08 20:31:01 +00:00
2016-09-08 20:39:15 +00:00
const assertBoundsEqual = (actual, expect) => {
if (!isScaleFactorRounding()) {
2018-09-13 16:10:51 +00:00
assert.deepStrictEqual(expect, actual)
2016-09-08 20:33:43 +00:00
} else if (Array.isArray(actual)) {
2016-09-08 20:39:15 +00:00
assertWithinDelta(actual[0], expect[0], 1, 'x')
assertWithinDelta(actual[1], expect[1], 1, 'y')
2016-09-08 20:31:01 +00:00
} else {
2016-09-08 20:39:15 +00:00
assertWithinDelta(actual.x, expect.x, 1, 'x')
assertWithinDelta(actual.y, expect.y, 1, 'y')
assertWithinDelta(actual.width, expect.width, 1, 'width')
assertWithinDelta(actual.height, expect.height, 1, 'height')
2016-09-08 20:31:01 +00:00
}
}
2016-09-08 20:39:15 +00:00
const assertWithinDelta = (actual, expect, delta, label) => {
2016-09-08 20:46:55 +00:00
const result = Math.abs(actual - expect)
assert.ok(result <= delta, `${label} value of ${actual} was not within ${delta} of ${expect}`)
2016-09-08 20:31:01 +00:00
}
// Is the display's scale factor possibly causing rounding of pixel coordinate
// values?
const isScaleFactorRounding = () => {
2018-09-13 16:10:51 +00:00
const { scaleFactor } = screen.getPrimaryDisplay()
// Return true if scale factor is non-integer value
2016-09-09 00:12:53 +00:00
if (Math.round(scaleFactor) !== scaleFactor) return true
// Return true if scale factor is odd number above 2
return scaleFactor > 2 && scaleFactor % 2 === 1
2016-09-08 20:31:01 +00:00
}
function serveFileFromProtocol (protocolName, filePath) {
return new Promise((resolve, reject) => {
protocol.registerBufferProtocol(protocolName, (request, callback) => {
2017-11-23 22:22:43 +00:00
// Disabled due to false positive in StandardJS
// eslint-disable-next-line standard/no-callback-literal
callback({
mimeType: 'text/html',
data: fs.readFileSync(filePath)
})
}, (error) => {
if (error != null) {
reject(error)
} else {
resolve()
}
})
})
}