'use strict'
const chai = require('chai')
const dirtyChai = require('dirty-chai')
const fs = require('fs')
const path = require('path')
const os = require('os')
const qs = require('querystring')
const http = require('http')
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
const features = process.electronBinding('features')
const { expect } = chai
const isCI = remote.getGlobal('isCi')
const nativeModulesEnabled = remote.getGlobal('nativeModulesEnabled')
chai.use(dirtyChai)
describe('BrowserWindow module', () => {
const fixtures = path.resolve(__dirname, 'fixtures')
let w = null
let iw = null
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 })
}
before((done) => {
const filePath = path.join(fixtures, 'pages', 'a.html')
const fileStats = fs.statSync(filePath)
postData = [
{
type: 'rawData',
bytes: Buffer.from('username=test&file=')
},
{
type: 'file',
filePath: filePath,
offset: 0,
length: fileStats.size,
modificationTime: fileStats.mtime.getTime() / 1000
}
]
server = http.createServer((req, res) => {
function respond () {
if (req.method === 'POST') {
let body = ''
req.on('data', (data) => {
if (data) body += data
})
req.on('end', () => {
const parsedData = qs.parse(body)
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(`
`)
} else if (req.url === '/cross-site') {
res.end(`${req.url}
`)
} else {
res.end()
}
}
setTimeout(respond, req.url.includes('slow') ? 200 : 0)
})
server.listen(0, '127.0.0.1', () => {
server.url = `http://127.0.0.1:${server.address().port}`
done()
})
})
after(() => {
server.close()
server = null
})
beforeEach(openTheWindow)
afterEach(closeTheWindow)
describe('BrowserWindow constructor', () => {
it('allows passing void 0 as the webContents', async () => {
await openTheWindow({
webContents: void 0
})
})
})
describe('BrowserWindow.close()', () => {
let server
before((done) => {
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('Hello')
break
default:
done('unsupported endpoint')
}
}).listen(0, '127.0.0.1', () => {
server.url = 'http://127.0.0.1:' + server.address().port
done()
})
})
after(() => {
server.close()
server = null
})
it('should emit unload handler', (done) => {
w.webContents.once('did-finish-load', () => { w.close() })
w.once('closed', () => {
const test = path.join(fixtures, 'api', 'unload')
const content = fs.readFileSync(test)
fs.unlinkSync(test)
expect(String(content)).to.equal('unload')
done()
})
w.loadFile(path.join(fixtures, 'api', 'unload.html'))
})
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'))
})
it('should not crash when invoked synchronously inside navigation observer', (done) => {
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` },
{ 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'
function * genNavigationEvent () {
let eventOptions = null
while ((eventOptions = events.shift()) && events.length) {
const w = new BrowserWindow({ show: false })
eventOptions.id = w.id
eventOptions.responseEvent = responseEvent
ipcRenderer.send('test-webcontents-navigation-observer', eventOptions)
yield 1
}
}
const gen = genNavigationEvent()
ipcRenderer.on(responseEvent, () => {
if (!gen.next().value) done()
})
gen.next()
})
})
describe('window.close()', () => {
it('should emit unload handler', (done) => {
w.once('closed', () => {
const test = path.join(fixtures, 'api', 'close')
const content = fs.readFileSync(test)
fs.unlinkSync(test)
expect(String(content)).to.equal('close')
done()
})
w.loadFile(path.join(fixtures, 'api', 'close.html'))
})
it('should emit beforeunload handler', (done) => {
w.once('onbeforeunload', () => { done() })
w.loadFile(path.join(fixtures, 'api', 'close-beforeunload-false.html'))
})
})
describe('BrowserWindow.destroy()', () => {
it('prevents users to access methods of webContents', () => {
const contents = w.webContents
w.destroy()
expect(() => {
contents.getProcessId()
}).to.throw('Object has been destroyed')
})
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 })
})
})
describe('BrowserWindow.loadURL(url)', () => {
it('should emit did-start-loading event', (done) => {
w.webContents.on('did-start-loading', () => { done() })
w.loadURL('about:blank')
})
it('should emit ready-to-show event', (done) => {
w.on('ready-to-show', () => { done() })
w.loadURL('about:blank')
})
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) => {
expect(code).to.equal(-6)
expect(desc).to.equal('ERR_FILE_NOT_FOUND')
expect(isMainFrame).to.be.true()
done()
})
w.loadURL('file://a.txt')
})
it('should emit did-fail-load event for invalid URL', (done) => {
w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
expect(desc).to.equal('ERR_INVALID_URL')
expect(code).to.equal(-300)
expect(isMainFrame).to.be.true()
done()
})
w.loadURL('http://example:port')
})
it('should set `mainFrame = false` on did-fail-load events in iframes', (done) => {
w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
expect(isMainFrame).to.be.false()
done()
})
w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html'))
})
it('does not crash in did-fail-provisional-load handler', (done) => {
w.webContents.once('did-fail-provisional-load', () => {
w.loadURL('http://127.0.0.1:11111')
done()
})
w.loadURL('http://127.0.0.1:11111')
})
it('should emit did-fail-load event for URL exceeding character limit', (done) => {
w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
expect(desc).to.equal('ERR_INVALID_URL')
expect(code).to.equal(-300)
expect(isMainFrame).to.be.true()
done()
})
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64')
w.loadURL(`data:image/png;base64,${data}`)
})
it('should return a promise', () => {
const p = w.loadURL('about:blank')
expect(p).to.have.property('then')
})
it('should return a promise that resolves', async () => {
expect(w.loadURL('about:blank')).to.eventually.be.fulfilled()
})
it('should return a promise that rejects on a load failure', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64')
const p = w.loadURL(`data:image/png;base64,${data}`)
await expect(p).to.eventually.be.rejected()
})
it('should return a promise that resolves even if pushState occurs during navigation', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64')
const p = w.loadURL('data:text/html,')
await expect(p).to.eventually.be.fulfilled()
})
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
expect(details.requestHeaders['content-type']).to.equal('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
expect(details.requestHeaders['content-type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.be.true()
})
})
it('should support support base url for data urls', (done) => {
ipcMain.once('answer', (event, test) => {
expect(test).to.equal('test')
done()
})
w.loadURL('data:text/html,', { baseURLForDataURL: `file://${path.join(fixtures, 'api')}${path.sep}` })
})
})
describe('will-navigate event', () => {
it('allows the window to be closed from the event listener', (done) => {
ipcRenderer.send('close-on-will-navigate', w.id)
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.skip('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`)
})
})
describe('BrowserWindow.show()', () => {
before(function () {
if (isCI) {
this.skip()
}
})
it('should focus on window', () => {
w.show()
expect(w.isFocused()).to.be.true()
})
it('should make the window visible', () => {
w.show()
expect(w.isVisible()).to.be.true()
})
it('emits when window is shown', (done) => {
w.once('show', () => {
expect(w.isVisible()).to.be.true()
done()
})
w.show()
})
})
describe('BrowserWindow.hide()', () => {
before(function () {
if (isCI) {
this.skip()
}
})
it('should defocus on window', () => {
w.hide()
expect(w.isFocused()).to.be.false()
})
it('should make the window not visible', () => {
w.show()
w.hide()
expect(w.isVisible()).to.be.false()
})
it('emits when window is hidden', (done) => {
w.show()
w.once('hide', () => {
expect(w.isVisible()).to.be.false()
done()
})
w.hide()
})
})
describe('BrowserWindow.showInactive()', () => {
it('should not focus on window', () => {
w.showInactive()
expect(w.isFocused()).to.be.false()
})
})
describe('BrowserWindow.focus()', () => {
it('does not make the window become visible', () => {
expect(w.isVisible()).to.be.false()
w.focus()
expect(w.isVisible()).to.be.false()
})
})
describe('BrowserWindow.blur()', () => {
it('removes focus from window', () => {
w.blur()
expect(w.isFocused()).to.be.false()
})
})
describe('BrowserWindow.getFocusedWindow()', () => {
it('returns the opener window when dev tools window is focused', (done) => {
w.show()
w.webContents.once('devtools-focused', () => {
expect(BrowserWindow.getFocusedWindow()).to.equal(w)
done()
})
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
expect(w.isFocused()).to.be.false()
const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' })
const otherWindowShown = emittedOnce(otherWindow, 'show')
otherWindow.loadURL('data:text/html,')
otherWindow.show()
await otherWindowShown
expect(otherWindow.isFocused()).to.be.true()
w.moveTop()
const wPos = w.getPosition()
const wMoving = emittedOnce(w, 'move')
w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta)
await wMoving
expect(w.isFocused()).to.be.false()
expect(otherWindow.isFocused()).to.be.true()
const wFocused = emittedOnce(w, 'focus')
w.focus()
await wFocused
expect(w.isFocused()).to.be.true()
otherWindow.moveTop()
const otherWindowPos = otherWindow.getPosition()
const otherWindowMoving = emittedOnce(otherWindow, 'move')
otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta)
await otherWindowMoving
expect(otherWindow.isFocused()).to.be.false()
expect(w.isFocused()).to.be.true()
await closeWindow(otherWindow, { assertSingleWindow: false }).then(() => {
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(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
})
expect(image.isEmpty()).to.be.true()
})
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,')
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)
})
})
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)
expectBoundsEqual(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)
expectBoundsEqual(w.getBounds(), expectedBounds)
})
})
describe('BrowserWindow.setSize(width, height)', () => {
it('sets the window size', async () => {
const size = [300, 400]
const resized = emittedOnce(w, 'resize')
w.setSize(size[0], size[1])
await resized
expectBoundsEqual(w.getSize(), size)
})
})
describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => {
it('sets the maximum and minimum size of the window', () => {
expect(w.getMinimumSize()).to.deep.equal([0, 0])
expect(w.getMaximumSize()).to.deep.equal([0, 0])
w.setMinimumSize(100, 100)
expectBoundsEqual(w.getMinimumSize(), [100, 100])
expectBoundsEqual(w.getMaximumSize(), [0, 0])
w.setMaximumSize(900, 600)
expectBoundsEqual(w.getMinimumSize(), [100, 100])
expectBoundsEqual(w.getMaximumSize(), [900, 600])
})
})
describe('BrowserWindow.setAspectRatio(ratio)', () => {
it('resets the behaviour when passing in 0', (done) => {
const size = [300, 400]
w.setAspectRatio(1 / 2)
w.setAspectRatio(0)
w.once('resize', () => {
expectBoundsEqual(w.getSize(), size)
done()
})
w.setSize(size[0], size[1])
})
})
describe('BrowserWindow.setPosition(x, y)', () => {
it('sets the window position', (done) => {
const pos = [10, 10]
w.once('move', () => {
const newPos = w.getPosition()
expect(newPos).to.deep.equal(pos)
done()
})
w.setPosition(pos[0], pos[1])
})
})
describe('BrowserWindow.setContentSize(width, height)', () => {
it('sets the content size', () => {
const size = [400, 400]
w.setContentSize(size[0], size[1])
const after = w.getContentSize()
expect(after).to.deep.equal(size)
})
it('works for a frameless window', () => {
w.destroy()
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400
})
const size = [400, 400]
w.setContentSize(size[0], size[1])
const after = w.getContentSize()
expect(after).to.deep.equal(size)
})
})
describe('BrowserWindow.setContentBounds(bounds)', () => {
it('sets the content size and position', (done) => {
const bounds = { x: 10, y: 10, width: 250, height: 250 }
w.once('resize', () => {
expectBoundsEqual(w.getContentBounds(), bounds)
done()
})
w.setContentBounds(bounds)
})
it('works for a frameless window', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300
})
const bounds = { x: 10, y: 10, width: 250, height: 250 }
w.once('resize', () => {
expect(w.getContentBounds()).to.deep.equal(bounds)
done()
})
w.setContentBounds(bounds)
})
})
describe(`BrowserWindow.getNormalBounds()`, () => {
describe(`Normal state`, () => {
it(`checks normal bounds after resize`, (done) => {
const size = [300, 400]
w.once('resize', () => {
expectBoundsEqual(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', () => {
expectBoundsEqual(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', () => {
expectBoundsEqual(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', () => {
expectBoundsEqual(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', () => {
expectBoundsEqual(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', () => {
expectBoundsEqual(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', () => {
expectBoundsEqual(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', () => {
expectBoundsEqual(w.getNormalBounds(), bounds)
done()
})
w.show()
w.setFullScreen(true)
})
})
})
describe('BrowserWindow.setProgressBar(progress)', () => {
it('sets the progress', () => {
expect(() => {
if (process.platform === 'darwin') {
app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'))
}
w.setProgressBar(0.5)
if (process.platform === 'darwin') {
app.dock.setIcon(null)
}
w.setProgressBar(-1)
}).to.not.throw()
})
it('sets the progress using "paused" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'paused' })
}).to.not.throw()
})
it('sets the progress using "error" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'error' })
}).to.not.throw()
})
it('sets the progress using "normal" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'normal' })
}).to.not.throw()
})
})
describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
it('sets the window as always on top', () => {
expect(w.isAlwaysOnTop()).to.be.false()
w.setAlwaysOnTop(true, 'screen-saver')
expect(w.isAlwaysOnTop()).to.be.true()
w.setAlwaysOnTop(false)
expect(w.isAlwaysOnTop()).to.be.false()
w.setAlwaysOnTop(true)
expect(w.isAlwaysOnTop()).to.be.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
}
expect(() => {
w.setAlwaysOnTop(true, '', -2147483644)
}).to.throw()
expect(() => {
w.setAlwaysOnTop(true, '', 2147483632)
}).to.throw()
})
})
describe('BrowserWindow.alwaysOnTop() resets level on minimize', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('resets the windows level on minimize', () => {
expect(w.isAlwaysOnTop()).to.be.false()
w.setAlwaysOnTop(true, 'screen-saver')
expect(w.isAlwaysOnTop()).to.be.true()
w.minimize()
expect(w.isAlwaysOnTop()).to.be.false()
w.restore()
expect(w.isAlwaysOnTop()).to.be.true()
})
})
describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
describe('on macOS', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('allows changing cursor auto-hiding', () => {
expect(() => {
w.setAutoHideCursor(false)
w.setAutoHideCursor(true)
}).to.not.throw()
})
})
describe('on non-macOS platforms', () => {
before(function () {
if (process.platform === 'darwin') {
this.skip()
}
})
it('is not available', () => {
expect(w.setAutoHideCursor).to.be.undefined()
})
})
})
describe('BrowserWindow.selectPreviousTab()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', () => {
expect(() => {
w.selectPreviousTab()
}).to.not.throw()
})
})
describe('BrowserWindow.selectNextTab()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', () => {
expect(() => {
w.selectNextTab()
}).to.not.throw()
})
})
describe('BrowserWindow.mergeAllWindows()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', () => {
expect(() => {
w.mergeAllWindows()
}).to.not.throw()
})
})
describe('BrowserWindow.moveTabToNewWindow()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', () => {
expect(() => {
w.moveTabToNewWindow()
}).to.not.throw()
})
})
describe('BrowserWindow.toggleTabBar()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', () => {
expect(() => {
w.toggleTabBar()
}).to.not.throw()
})
})
describe('BrowserWindow.addTabbedWindow()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', (done) => {
const tabbedWindow = new BrowserWindow({})
expect(() => {
w.addTabbedWindow(tabbedWindow)
}).to.not.throw()
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(3) // Test window + w + tabbedWindow
closeWindow(tabbedWindow, { assertSingleWindow: false }).then(() => {
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2) // Test window + w
done()
})
})
it('throws when called on itself', () => {
expect(() => {
w.addTabbedWindow(w)
}).to.throw('AddTabbedWindow cannot be called by a window on itself.')
})
})
describe('BrowserWindow.setWindowButtonVisibility()', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('does not throw', () => {
expect(() => {
w.setWindowButtonVisibility(true)
w.setWindowButtonVisibility(false)
}).to.not.throw()
})
it('throws with custom title bar buttons', () => {
expect(() => {
w.destroy()
w = new BrowserWindow({
show: false,
titleBarStyle: 'customButtonsOnHover',
frame: false
})
w.setWindowButtonVisibility(true)
}).to.throw('Not supported for this window')
})
})
describe('BrowserWindow.setVibrancy(type)', () => {
it('allows setting, changing, and removing the vibrancy', () => {
expect(() => {
w.setVibrancy('light')
w.setVibrancy('dark')
w.setVibrancy(null)
w.setVibrancy('ultra-dark')
w.setVibrancy('')
}).to.not.throw()
})
})
describe('BrowserWindow.setAppDetails(options)', () => {
before(function () {
if (process.platform !== 'win32') {
this.skip()
}
})
it('supports setting the app details', () => {
const iconPath = path.join(fixtures, 'assets', 'icon.ico')
expect(() => {
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({})
}).to.not.throw()
expect(() => {
w.setAppDetails()
}).to.throw('Insufficient number of arguments.')
})
})
describe('BrowserWindow.fromId(id)', () => {
it('returns the window with id', () => {
expect(BrowserWindow.fromId(w.id).id).to.equal(w.id)
})
})
describe('BrowserWindow.fromWebContents(webContents)', () => {
let contents = null
beforeEach(() => { contents = webContents.create({}) })
afterEach(() => { contents.destroy() })
it('returns the window with the webContents', () => {
expect(BrowserWindow.fromWebContents(w.webContents).id).to.equal(w.id)
expect(BrowserWindow.fromWebContents(contents)).to.be.undefined()
})
})
describe('BrowserWindow.fromDevToolsWebContents(webContents)', () => {
let contents = null
beforeEach(() => { contents = webContents.create({}) })
afterEach(() => { contents.destroy() })
it('returns the window with the webContents', (done) => {
w.webContents.once('devtools-opened', () => {
expect(BrowserWindow.fromDevToolsWebContents(w.devToolsWebContents).id).to.equal(w.id)
expect(BrowserWindow.fromDevToolsWebContents(w.webContents)).to.be.undefined()
expect(BrowserWindow.fromDevToolsWebContents(contents)).to.be.undefined()
done()
})
w.webContents.openDevTools()
})
})
describe('BrowserWindow.openDevTools()', () => {
it('does not crash for frameless window', () => {
w.destroy()
w = new BrowserWindow({ show: false })
w.openDevTools()
})
})
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', () => {
expect(BrowserWindow.fromBrowserView(bv).id).to.equal(w.id)
})
it('returns undefined if not attached', () => {
w.setBrowserView(null)
expect(BrowserWindow.fromBrowserView(bv)).to.be.null()
})
})
describe('BrowserWindow.setOpacity(opacity)', () => {
it('make window with initial opacity', () => {
w.destroy()
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
opacity: 0.5
})
expect(w.getOpacity()).to.equal(0.5)
})
it('allows setting the opacity', () => {
expect(() => {
w.setOpacity(0.0)
expect(w.getOpacity()).to.equal(0.0)
w.setOpacity(0.5)
expect(w.getOpacity()).to.equal(0.5)
w.setOpacity(1.0)
expect(w.getOpacity()).to.equal(1.0)
}).to.not.throw()
})
})
describe('BrowserWindow.setShape(rects)', () => {
it('allows setting shape', () => {
expect(() => {
w.setShape([])
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([])
}).to.not.throw()
})
})
describe('"useContentSize" option', () => {
it('make window created with content size when used', () => {
w.destroy()
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
useContentSize: true
})
const contentSize = w.getContentSize()
expect(contentSize).to.deep.equal([400, 400])
})
it('make window created with window size when not used', () => {
const size = w.getSize()
expect(size).to.deep.equal([400, 400])
})
it('works for a frameless window', () => {
w.destroy()
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400,
useContentSize: true
})
const contentSize = w.getContentSize()
expect(contentSize).to.deep.equal([400, 400])
const size = w.getSize()
expect(size).to.deep.equal([400, 400])
})
})
describe('"titleBarStyle" option', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
if (parseInt(os.release().split('.')[0]) < 14) {
this.skip()
}
})
it('creates browser window with hidden title bar', () => {
w.destroy()
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden'
})
const contentSize = w.getContentSize()
expect(contentSize).to.deep.equal([400, 400])
})
it('creates browser window with hidden inset title bar', () => {
w.destroy()
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hiddenInset'
})
const contentSize = w.getContentSize()
expect(contentSize).to.deep.equal([400, 400])
})
})
describe('enableLargerThanScreen" option', () => {
before(function () {
if (process.platform === 'linux') {
this.skip()
}
})
beforeEach(() => {
w.destroy()
w = new BrowserWindow({
show: true,
width: 400,
height: 400,
enableLargerThanScreen: true
})
})
it('can move the window out of screen', () => {
w.setPosition(-10, -10)
const after = w.getPosition()
expect(after).to.deep.equal([-10, -10])
})
it('can set the window larger than screen', () => {
const size = screen.getPrimaryDisplay().size
size.width += 100
size.height += 100
w.setSize(size.width, size.height)
expectBoundsEqual(w.getSize(), [size.width, size.height])
})
})
describe('"zoomToPageWidth" option', () => {
before(function () {
if (process.platform !== 'darwin') {
this.skip()
}
})
it('sets the window width to the page width when used', () => {
w.destroy()
w = new BrowserWindow({
show: false,
width: 500,
height: 400,
zoomToPageWidth: true
})
w.maximize()
expect(w.getSize()[0]).to.equal(500)
})
})
describe('"tabbingIdentifier" option', () => {
it('can be set on a window', () => {
w.destroy()
w = new BrowserWindow({
tabbingIdentifier: 'group1'
})
w.destroy()
w = new BrowserWindow({
tabbingIdentifier: 'group2',
frame: false
})
})
})
describe('"webPreferences" option', () => {
afterEach(() => { ipcMain.removeAllListeners('answer') })
describe('"preload" option', () => {
const doesNotLeakSpec = (name, webPrefs) => {
it(name, async function () {
w.destroy()
w = new BrowserWindow({
webPreferences: {
...webPrefs,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
})
const leakResult = emittedOnce(ipcMain, 'leak-result')
w.loadFile(path.join(fixtures, 'api', 'no-leak.html'))
const [, result] = await leakResult
expect(result).to.have.property('require', 'undefined')
expect(result).to.have.property('exports', 'undefined')
expect(result).to.have.property('windowExports', 'undefined')
expect(result).to.have.property('windowPreload', 'undefined')
expect(result).to.have.property('windowRequire', 'undefined')
})
}
doesNotLeakSpec('does not leak require', {
nodeIntegration: false,
sandbox: false,
contextIsolation: false
})
doesNotLeakSpec('does not leak require when sandbox is enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: false
})
doesNotLeakSpec('does not leak require when context isolation is enabled', {
nodeIntegration: false,
sandbox: false,
contextIsolation: true
})
doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: true
})
it('loads the script before other scripts in window', async () => {
const preload = path.join(fixtures, 'module', 'set-global.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).to.eql('preload')
})
it('can successfully delete the Buffer global', async () => {
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')
})
})
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(() => {
expect(defaultSession.getPreloads()).to.deep.equal([])
defaultSession.setPreloads(preloads)
})
afterEach(() => {
defaultSession.setPreloads([])
})
it('can set multiple session preload script', function () {
expect(defaultSession.getPreloads()).to.deep.equal(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) {
expect(preload1).to.equal('preload-1')
expect(preload2).to.equal('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) => {
expect(argv).to.include('--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) => {
expect(argv).to.include('--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'))
})
})
describe('"node-integration" option', () => {
it('disables node integration by default', (done) => {
const preload = path.join(fixtures, 'module', 'send-later.js')
ipcMain.once('answer', (event, typeofProcess, typeofBuffer) => {
expect(typeofProcess).to.equal('undefined')
expect(typeofBuffer).to.equal('undefined')
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload
}
})
w.loadFile(path.join(fixtures, 'api', 'blank.html'))
})
})
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)
})
describe('"sandbox" option', () => {
function waitForEvents (emitter, events, callback) {
let count = events.length
for (const event of events) {
emitter.once(event, () => {
if (!--count) callback()
})
}
}
const preload = path.join(fixtures, 'module', 'preload-sandbox.js')
it('exposes ipcRenderer to preload script', (done) => {
ipcMain.once('answer', function (event, test) {
expect(test).to.equal('preload')
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
})
w.loadFile(path.join(fixtures, 'api', 'preload.html'))
})
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) {
expect(test).to.equal('preload')
done()
})
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preloadSpecialChars
}
})
w.loadFile(path.join(fixtures, 'api', 'preload.html'))
})
it('exposes "loaded" event to preload script', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
})
ipcMain.once('process-loaded', () => done())
w.loadURL('about:blank')
})
it('exposes "exit" event to preload script', function (done) {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
})
const htmlPath = path.join(fixtures, 'api', 'sandbox.html?exit-event')
const pageUrl = 'file://' + htmlPath
ipcMain.once('answer', function (event, url) {
let expectedUrl = pageUrl
if (process.platform === 'win32') {
expectedUrl = 'file:///' + htmlPath.replace(/\\/g, '/')
}
expect(url).to.equal(expectedUrl)
done()
})
w.loadURL(pageUrl)
})
it('should open windows in same domain with cross-scripting enabled', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
})
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
const htmlPath = path.join(fixtures, 'api', 'sandbox.html?window-open')
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, '/')
}
expect(url).to.equal(expectedUrl)
expect(frameName).to.equal('popup!')
expect(options.width).to.equal(500)
expect(options.height).to.equal(600)
ipcMain.once('answer', function (event, html) {
expect(html).to.equal('scripting from opener
')
done()
})
})
w.loadURL(pageUrl)
})
it('should open windows in another domain with cross-scripting disabled', async () => {
const w = await openTheWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
})
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
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')
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
// 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.
const touchPopupResult = emittedOnce(ipcMain, 'answer')
w.webContents.send('touch-the-popup')
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 })
expect(popupAccessMessage).to.be.a('string',
`child's .document is accessible from its parent window`)
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/)
})
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) => {
expect(args).to.include('--enable-sandbox')
done()
})
w.loadFile(path.join(fixtures, 'api', 'new-window.html'))
})
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) => {
expect(webPreferences.foo).to.equal('bar')
done()
})
w.loadFile(path.join(fixtures, 'api', 'new-window.html'))
})
it('should set ipc event sender correctly', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
})
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
let childWc
w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
childWc = options.webContents
expect(w.webContents).to.not.equal(childWc)
})
ipcMain.once('parent-ready', function (event) {
expect(w.webContents).to.equal(event.sender)
event.sender.send('verified')
})
ipcMain.once('child-ready', function (event) {
expect(childWc).to.be.an('object')
expect(childWc).to.equal(event.sender)
event.sender.send('verified')
})
waitForEvents(ipcMain, [
'parent-answer',
'child-answer'
], done)
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'verify-ipc-sender' })
})
describe('event handling', () => {
it('works for window events', (done) => {
waitForEvents(w, [
'page-title-updated'
], done)
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'window-events' })
})
it('works for stop events', (done) => {
waitForEvents(w.webContents, [
'did-navigate',
'did-fail-load',
'did-stop-loading'
], done)
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'webcontents-stop' })
})
it('works for web contents events', (done) => {
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)
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'webcontents-events' })
})
})
it('supports calling preventDefault on new-window events', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
})
const initialWebContents = webContents.getAllWebContents().map((i) => i.id)
ipcRenderer.send('prevent-next-new-window', w.webContents.id)
w.webContents.once('new-window', () => {
// 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)
expect(currentWebContents).to.deep.equal(initialWebContents)
done()
}, 100)
})
w.loadFile(path.join(fixtures, 'pages', 'window-open.html'))
})
// see #9387
it('properly manages remote object references after page reload', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload,
sandbox: true
}
})
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'reload-remote' })
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')
expect(arg).to.equal('hi')
done()
})
})
it('properly manages remote object references after page reload in child window', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
preload,
sandbox: true
}
})
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
w.loadFile(path.join(fixtures, 'api', 'sandbox.html'), { search: 'reload-remote-child' })
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')
expect(arg).to.equal('hi child window')
done()
})
})
it('validates process APIs access in sandboxed renderer', (done) => {
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')
}
done()
})
remote.process.env.sandboxmain = 'foo'
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
})
w.webContents.once('preload-error', (event, preloadPath, error) => {
done(error)
})
w.loadFile(path.join(fixtures, 'api', 'preload.html'))
})
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)
})
})
describe('nativeWindowOpen option', () => {
beforeEach(() => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nativeWindowOpen: true
}
})
})
it('opens window of about:blank with cross-scripting enabled', (done) => {
ipcMain.once('answer', (event, content) => {
expect(content).to.equal('Hello')
done()
})
w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'))
})
it('opens window of same domain with cross-scripting enabled', (done) => {
ipcMain.once('answer', (event, content) => {
expect(content).to.equal('Hello')
done()
})
w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'))
})
it('blocks accessing cross-origin frames', (done) => {
ipcMain.once('answer', (event, content) => {
expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.')
done()
})
w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'))
})
it('opens window from