chore: remove promisification deprecation callbacks (#17907)

* chore: remove promisification deprecation callbacks

* update docs

* fix smoke test

* fix executejs issue

* cleanup leftovers

* fix webContents.executeJavaScript tests

* cleanup WebContents.prototype.takeHeapSnapshot

* fix "sets arbitrary webContents as devtools" test

* fix executeJavaScriptInFrame related tests
This commit is contained in:
Shelley Vohr 2019-04-30 07:08:33 -07:00 committed by John Kleinschmidt
parent fdf5f838f4
commit d87b3ead76
44 changed files with 94 additions and 1418 deletions

View file

@ -547,19 +547,6 @@ describe('BrowserWindow module', () => {
expect(image.isEmpty()).to.be.true()
})
// 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,
@ -579,30 +566,6 @@ describe('BrowserWindow module', () => {
// 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()
})
})
})
})
})
describe('BrowserWindow.setBounds(bounds[, animate])', () => {
@ -3096,13 +3059,14 @@ describe('BrowserWindow module', () => {
w.destroy()
w = new BrowserWindow()
w.webContents.once('did-finish-load', () => {
w.once('enter-full-screen', () => {
w.once('leave-html-full-screen', () => {
done()
w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true).then(() => {
w.once('enter-full-screen', () => {
w.once('leave-html-full-screen', () => {
done()
})
w.setFullScreen(false)
})
w.setFullScreen(false)
})
w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true)
})
w.loadURL('about:blank')
})
@ -3265,7 +3229,7 @@ describe('BrowserWindow module', () => {
const lastPanelId = UI.inspectorView._tabbedPane._tabs.peekLast().id
UI.inspectorView.showPanel(lastPanelId)
}
devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false, () => {
devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false).then(() => {
showPanelTimeoutId = setTimeout(show, 100)
})
}
@ -3466,47 +3430,22 @@ describe('BrowserWindow module', () => {
URIError
])
it('doesnt throw when no calback is provided', () => {
const result = ipcRenderer.sendSync('executeJavaScript', code, false)
assert.strictEqual(result, 'success')
})
it('returns result when calback is provided', (done) => {
ipcRenderer.send('executeJavaScript', code, true)
ipcRenderer.once('executeJavaScript-response', function (event, result) {
assert.strictEqual(result, expected)
done()
})
})
it('returns result if the code returns an asyncronous promise', (done) => {
ipcRenderer.send('executeJavaScript', asyncCode, true)
ipcRenderer.once('executeJavaScript-response', (event, result) => {
assert.strictEqual(result, expected)
done()
})
})
it('resolves the returned promise with the result when a callback is specified', (done) => {
ipcRenderer.send('executeJavaScript', code, true)
ipcRenderer.once('executeJavaScript-promise-response', (event, result) => {
assert.strictEqual(result, expected)
done()
})
})
it('resolves the returned promise with the result when no callback is specified', (done) => {
ipcRenderer.send('executeJavaScript', code, false)
it('resolves the returned promise with the result', (done) => {
ipcRenderer.send('executeJavaScript', code)
ipcRenderer.once('executeJavaScript-promise-response', (event, result) => {
assert.strictEqual(result, expected)
done()
})
})
it('resolves the returned promise with the result if the code returns an asyncronous promise', (done) => {
ipcRenderer.send('executeJavaScript', asyncCode, true)
ipcRenderer.send('executeJavaScript', asyncCode)
ipcRenderer.once('executeJavaScript-promise-response', (event, result) => {
assert.strictEqual(result, expected)
done()
})
})
it('rejects the returned promise if an async error is thrown', (done) => {
ipcRenderer.send('executeJavaScript', badAsyncCode, true)
ipcRenderer.send('executeJavaScript', badAsyncCode)
ipcRenderer.once('executeJavaScript-promise-error', (event, error) => {
assert.strictEqual(error, expectedErrorMsg)
done()
@ -3515,7 +3454,7 @@ describe('BrowserWindow module', () => {
it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
for (const error in errorTypes) {
await new Promise((resolve) => {
ipcRenderer.send('executeJavaScript', `Promise.reject(new ${error.name}("Wamp-wamp")`, true)
ipcRenderer.send('executeJavaScript', `Promise.reject(new ${error.name}("Wamp-wamp")`)
ipcRenderer.once('executeJavaScript-promise-error-name', (event, name) => {
assert.strictEqual(name, error.name)
resolve()
@ -3523,6 +3462,7 @@ describe('BrowserWindow module', () => {
})
}
})
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
@ -3530,23 +3470,25 @@ describe('BrowserWindow module', () => {
var iframe = document.createElement('iframe')
iframe.src = '${server.url}/slow'
document.body.appendChild(iframe)
`, () => {
w.webContents.executeJavaScript('console.log(\'hello\')', () => {
`).then(() => {
w.webContents.executeJavaScript('console.log(\'hello\')').then(() => {
done()
})
})
})
w.loadURL(server.url)
})
it('executes after page load', (done) => {
w.webContents.executeJavaScript(code, (result) => {
w.webContents.executeJavaScript(code).then(result => {
assert.strictEqual(result, expected)
done()
})
w.loadURL(server.url)
})
it('works with result objects that have DOM class prototypes', (done) => {
w.webContents.executeJavaScript('document.location', (result) => {
w.webContents.executeJavaScript('document.location').then(result => {
assert.strictEqual(result.origin, server.url)
assert.strictEqual(result.protocol, 'http:')
done()

View file

@ -38,35 +38,6 @@ describe('contentTracing', () => {
return resultFilePath
}
// TODO(codebytere): remove when promisification is complete
const recordCallback = async (options, outputFilePath, recordTimeInMilliseconds = 1e3) => {
await app.whenReady()
await startRecording(options)
await timeout(recordTimeInMilliseconds)
const resultFilePath = await stopRecording(outputFilePath)
return resultFilePath
}
// TODO(codebytere): remove when promisification is complete
const startRecording = async (options) => {
return new Promise((resolve) => {
contentTracing.startRecording(options, () => {
resolve()
})
})
}
// TODO(codebytere): remove when promisification is complete
const stopRecording = async (filePath) => {
return new Promise((resolve) => {
contentTracing.stopRecording(filePath, (resultFilePath) => {
resolve(resultFilePath)
})
})
}
const outputFilePath = getPathInATempFolder('trace.json')
beforeEach(() => {
if (fs.existsSync(outputFilePath)) {
@ -95,18 +66,6 @@ describe('contentTracing', () => {
`the trace output file is empty, check "${outputFilePath}"`)
})
// TODO(codebytere): remove when promisification is complete
it('accepts an empty config (callback)', async () => {
const config = {}
await recordCallback(config, outputFilePath)
expect(fs.existsSync(outputFilePath)).to.be.true()
const fileSizeInKiloBytes = getFileSizeInKiloBytes(outputFilePath)
expect(fileSizeInKiloBytes).to.be.above(0,
`the trace output file is empty, check "${outputFilePath}"`)
})
it('accepts a trace config', async () => {
// (alexeykuzmin): All categories are excluded on purpose,
// so only metadata gets into the output file.
@ -129,29 +88,6 @@ describe('contentTracing', () => {
check "${outputFilePath}"`)
})
// TODO(codebytere): remove when promisification is complete
it('accepts a trace config (callback)', async () => {
// (alexeykuzmin): All categories are excluded on purpose,
// so only metadata gets into the output file.
const config = {
excluded_categories: ['*']
}
await recordCallback(config, outputFilePath)
expect(fs.existsSync(outputFilePath)).to.be.true()
// If the `excluded_categories` param above is not respected
// the file size will be above 50KB.
const fileSizeInKiloBytes = getFileSizeInKiloBytes(outputFilePath)
const expectedMaximumFileSize = 10 // Depends on a platform.
expect(fileSizeInKiloBytes).to.be.above(0,
`the trace output file is empty, check "${outputFilePath}"`)
expect(fileSizeInKiloBytes).to.be.below(expectedMaximumFileSize,
`the trace output file is suspiciously large (${fileSizeInKiloBytes}KB),
check "${outputFilePath}"`)
})
it('accepts "categoryFilter" and "traceOptions" as a config', async () => {
// (alexeykuzmin): All categories are excluded on purpose,
// so only metadata gets into the output file.
@ -174,30 +110,6 @@ describe('contentTracing', () => {
`the trace output file is suspiciously large (${fileSizeInKiloBytes}KB),
check "${outputFilePath}"`)
})
// TODO(codebytere): remove when promisification is complete
it('accepts "categoryFilter" and "traceOptions" as a config (callback)', async () => {
// (alexeykuzmin): All categories are excluded on purpose,
// so only metadata gets into the output file.
const config = {
categoryFilter: '__ThisIsANonexistentCategory__',
traceOptions: ''
}
await recordCallback(config, outputFilePath)
expect(fs.existsSync(outputFilePath)).to.be.true()
// If the `categoryFilter` param above is not respected
// the file size will be above 50KB.
const fileSizeInKiloBytes = getFileSizeInKiloBytes(outputFilePath)
const expectedMaximumFileSize = 10 // Depends on a platform.
expect(fileSizeInKiloBytes).to.be.above(0,
`the trace output file is empty, check "${outputFilePath}"`)
expect(fileSizeInKiloBytes).to.be.below(expectedMaximumFileSize,
`the trace output file is suspiciously large (${fileSizeInKiloBytes}KB),
check "${outputFilePath}"`)
})
})
describe('stopRecording', function () {
@ -208,12 +120,6 @@ describe('contentTracing', () => {
expect(resultFilePath).to.be.a('string').and.be.equal(outputFilePath)
})
// TODO(codebytere): remove when promisification is complete
it('calls its callback with a result file path (callback)', async () => {
const resultFilePath = await recordCallback(/* options */ {}, outputFilePath)
expect(resultFilePath).to.be.a('string').and.be.equal(outputFilePath)
})
it('creates a temporary file when an empty string is passed', async function () {
const resultFilePath = await record(/* options */ {}, /* outputFilePath */ '')
expect(resultFilePath).to.be.a('string').that.is.not.empty()

View file

@ -116,28 +116,6 @@ describe('debugger module', () => {
w.webContents.debugger.detach()
})
// TODO(miniak): remove when promisification is complete
it('returns response (callback)', done => {
w.webContents.loadURL('about:blank')
try {
w.webContents.debugger.attach()
} catch (err) {
return done(`unexpected error : ${err}`)
}
const callback = (err, res) => {
expect(err).to.be.null()
expect(res.wasThrown).to.be.undefined()
expect(res.result.value).to.equal(6)
w.webContents.debugger.detach()
done()
}
const params = { 'expression': '4+2' }
w.webContents.debugger.sendCommand('Runtime.evaluate', params, callback)
})
it('returns response when devtools is opened', async () => {
w.webContents.loadURL('about:blank')
w.webContents.debugger.attach()
@ -155,28 +133,6 @@ describe('debugger module', () => {
w.webContents.debugger.detach()
})
// TODO(miniak): remove when promisification is complete
it('returns response when devtools is opened (callback)', done => {
w.webContents.loadURL('about:blank')
try {
w.webContents.debugger.attach()
} catch (err) {
return done(`unexpected error : ${err}`)
}
const callback = (err, res) => {
expect(err).to.be.null()
expect(res.wasThrown).to.be.undefined()
expect(res.result.value).to.equal(6)
w.webContents.debugger.detach()
done()
}
w.webContents.openDevTools()
w.webContents.once('devtools-opened', () => {
const params = { 'expression': '4+2' }
w.webContents.debugger.sendCommand('Runtime.evaluate', params, callback)
})
})
it('fires message event', done => {
const url = process.platform !== 'win32'
? `file://${path.join(fixtures, 'pages', 'a.html')}`
@ -212,22 +168,6 @@ describe('debugger module', () => {
w.webContents.debugger.detach()
})
// TODO(miniak): remove when promisification is complete
it('returns error message when command fails (callback)', done => {
w.webContents.loadURL('about:blank')
try {
w.webContents.debugger.attach()
} catch (err) {
done(`unexpected error : ${err}`)
}
w.webContents.debugger.sendCommand('Test', (err, res) => {
expect(err).to.be.an.instanceOf(Error).with.property('message', "'Test' wasn't found")
w.webContents.debugger.detach()
done()
})
})
it('handles valid unicode characters in message', (done) => {
try {
w.webContents.debugger.attach()
@ -239,7 +179,7 @@ describe('debugger module', () => {
if (method === 'Network.loadingFinished') {
w.webContents.debugger.sendCommand('Network.getResponseBody', {
requestId: params.requestId
}, (_, data) => {
}).then(data => {
expect(data.body).to.equal('\u0024')
done()
})

View file

@ -30,15 +30,6 @@ describe('desktopCapturer', () => {
expect(sources).to.be.an('array').that.is.not.empty()
})
// TODO(codebytere): remove when promisification is complete
it('should return a non-empty array of sources (callback)', (done) => {
desktopCapturer.getSources({ types: ['window', 'screen'] }, (err, sources) => {
expect(sources).to.be.an('array').that.is.not.empty()
expect(err).to.be.null()
done()
})
})
it('throws an error for invalid options', async () => {
const promise = desktopCapturer.getSources(['window', 'screen'])
expect(promise).to.be.eventually.rejectedWith(Error, 'Invalid options')
@ -60,20 +51,6 @@ describe('desktopCapturer', () => {
expect(promise2).to.not.eventually.be.rejected()
})
// TODO(codebytere): remove when promisification is complete
it('responds to subsequent calls of different options (callback)', (done) => {
let callCount = 0
const callback = (err, sources) => {
callCount++
expect(err).to.be.null()
expect(sources).to.not.be.null()
if (callCount === 2) done()
}
desktopCapturer.getSources({ types: ['window'] }, callback)
desktopCapturer.getSources({ types: ['screen'] }, callback)
})
it('returns an empty display_id for window sources on Windows and Mac', async () => {
// Linux doesn't return any window sources.
if (process.platform !== 'win32' && process.platform !== 'darwin') return

View file

@ -43,37 +43,13 @@ describe('inAppPurchase module', function () {
expect(success).to.be.false()
})
// TODO(codebytere): remove when promisification is complete
it('purchaseProduct() fails when buying invalid product (callback)', done => {
inAppPurchase.purchaseProduct('non-exist', 1, success => {
expect(success).to.be.false()
done()
})
})
it('purchaseProduct() accepts optional arguments', async () => {
const success = await inAppPurchase.purchaseProduct('non-exist')
expect(success).to.be.false()
})
// TODO(codebytere): remove when promisification is complete
it('purchaseProduct() accepts optional arguments (callback)', done => {
inAppPurchase.purchaseProduct('non-exist', success => {
expect(success).to.be.false()
done()
})
})
it('getProducts() returns an empty list when getting invalid product', async () => {
const products = await inAppPurchase.getProducts(['non-exist'])
expect(products).to.be.an('array').of.length(0)
})
// TODO(codebytere): remove when promisification is complete
it('getProducts() returns an empty list when getting invalid product (callback)', done => {
inAppPurchase.getProducts(['non-exist'], products => {
expect(products).to.be.an('array').of.length(0)
done()
})
})
})

View file

@ -78,27 +78,6 @@ describe('netLog module', () => {
expect(fs.existsSync(dumpFileDynamic)).to.be.true()
})
// TODO(miniak): remove when promisification is complete
it('should begin and end logging to file when .startLogging() and .stopLogging() is called (callback)', done => {
expect(netLog.currentlyLogging).to.be.false()
expect(netLog.currentlyLoggingPath).to.equal('')
netLog.startLogging(dumpFileDynamic)
expect(netLog.currentlyLogging).to.be.true()
expect(netLog.currentlyLoggingPath).to.equal(dumpFileDynamic)
netLog.stopLogging((path) => {
expect(netLog.currentlyLogging).to.be.false()
expect(netLog.currentlyLoggingPath).to.equal('')
expect(path).to.equal(dumpFileDynamic)
expect(fs.existsSync(dumpFileDynamic)).to.be.true()
done()
})
})
it('should silence when .stopLogging() is called without calling .startLogging()', async () => {
expect(netLog.currentlyLogging).to.be.false()
expect(netLog.currentlyLoggingPath).to.equal('')
@ -111,21 +90,6 @@ describe('netLog module', () => {
expect(path).to.equal('')
})
// TODO(miniak): remove when promisification is complete
it('should silence when .stopLogging() is called without calling .startLogging() (callback)', done => {
expect(netLog.currentlyLogging).to.be.false()
expect(netLog.currentlyLoggingPath).to.equal('')
netLog.stopLogging(path => {
expect(netLog.currentlyLogging).to.be.false()
expect(netLog.currentlyLoggingPath).to.equal('')
expect(path).to.equal('')
done()
})
})
it('should begin and end logging automatically when --log-net-log is passed', done => {
if (isCI && process.platform === 'linux') {
done()

View file

@ -686,27 +686,11 @@ describe('protocol module', () => {
assert.strictEqual(result, true)
})
// TODO(codebytere): remove when promisification is complete
it('returns true for about: (callback)', (done) => {
protocol.isProtocolHandled('about', (result) => {
assert.strictEqual(result, true)
done()
})
})
it('returns true for file:', async () => {
const result = await protocol.isProtocolHandled('file')
assert.strictEqual(result, true)
})
// TODO(codebytere): remove when promisification is complete
it('returns true for file: (callback)', (done) => {
protocol.isProtocolHandled('file', (result) => {
assert.strictEqual(result, true)
done()
})
})
it('returns true for http:', async () => {
const result = await protocol.isProtocolHandled('http')
assert.strictEqual(result, true)
@ -732,18 +716,6 @@ describe('protocol module', () => {
})
})
// TODO(codebytere): remove when promisification is complete
it('returns true for custom protocol (callback)', (done) => {
const emptyHandler = (request, callback) => callback()
protocol.registerStringProtocol(protocolName, emptyHandler, (error) => {
assert.strictEqual(error, null)
protocol.isProtocolHandled(protocolName, (result) => {
assert.strictEqual(result, true)
done()
})
})
})
it('returns true for intercepted protocol', (done) => {
const emptyHandler = (request, callback) => callback()
protocol.interceptStringProtocol('http', emptyHandler, async (error) => {
@ -753,18 +725,6 @@ describe('protocol module', () => {
done()
})
})
// TODO(codebytere): remove when promisification is complete
it('returns true for intercepted protocol (callback)', (done) => {
const emptyHandler = (request, callback) => callback()
protocol.interceptStringProtocol('http', emptyHandler, (error) => {
assert.strictEqual(error, null)
protocol.isProtocolHandled('http', (result) => {
assert.strictEqual(result, true)
done()
})
})
})
})
describe('protocol.intercept(Any)Protocol', () => {

View file

@ -71,7 +71,7 @@ describe('session module', () => {
const name = '0'
const value = '0'
it('should get cookies with promises', (done) => {
it('should get cookies', (done) => {
const server = http.createServer((req, res) => {
res.setHeader('Set-Cookie', [`${name}=${value}`])
res.end('finished')
@ -90,27 +90,7 @@ describe('session module', () => {
})
})
it('should get cookies with callbacks', (done) => {
const server = http.createServer((req, res) => {
res.setHeader('Set-Cookie', [`${name}=${value}`])
res.end('finished')
server.close()
})
server.listen(0, '127.0.0.1', () => {
w.webContents.once('did-finish-load', () => {
w.webContents.session.cookies.get({ url }, (error, list) => {
if (error) return done(error)
const cookie = list.find(cookie => cookie.name === name)
expect(cookie).to.exist.and.to.have.property('value', value)
done()
})
})
const { port } = server.address()
w.loadURL(`${url}:${port}`)
})
})
it('sets cookies with promises', async () => {
it('sets cookies', async () => {
const { cookies } = session.defaultSession
const name = '1'
const value = '1'
@ -118,13 +98,6 @@ describe('session module', () => {
await cookies.set({ url, name, value })
})
it('sets cookies with callbacks', (done) => {
const { cookies } = session.defaultSession
const name = '1'
const value = '1'
cookies.set({ url, name, value }, (error, list) => done(error))
})
it('yields an error when setting a cookie with missing required fields', async () => {
let error
try {
@ -150,7 +123,7 @@ describe('session module', () => {
}
})
it('should remove cookies with promises', async () => {
it('should remove cookies', async () => {
const { cookies } = session.defaultSession
const name = '2'
const value = '2'
@ -162,24 +135,6 @@ describe('session module', () => {
assert(!list.some(cookie => cookie.name === name && cookie.value === value))
})
it('should remove cookies with callbacks', (done) => {
const { cookies } = session.defaultSession
const name = '2'
const value = '2'
cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }, (error) => {
if (error) return done(error)
cookies.remove(url, name, (error) => {
if (error) return done(error)
cookies.get({ url }, (error, list) => {
if (error) return done(error)
assert(!list.some(cookie => cookie.name === name))
done()
})
})
})
})
it('should set cookie for standard scheme', async () => {
const { cookies } = session.defaultSession
const standardScheme = remote.getGlobal('standardScheme')
@ -220,39 +175,13 @@ describe('session module', () => {
})
describe('ses.cookies.flushStore()', async () => {
describe('flushes the cookies to disk and invokes the callback when done', async () => {
it('with promises', async () => {
const name = 'foo'
const value = 'bar'
const { cookies } = session.defaultSession
describe('flushes the cookies to disk', async () => {
const name = 'foo'
const value = 'bar'
const { cookies } = session.defaultSession
await cookies.set({ url, name, value })
await cookies.flushStore()
})
it('with callbacks', (done) => {
const name = 'foo'
const value = 'bar'
const { cookies } = session.defaultSession
cookies.set({ url, name, value }, (error) => {
if (error) return done(error)
cookies.flushStore(error => done(error))
})
})
})
})
describe('ses.cookies.flushStore(callback)', () => {
it('flushes the cookies to disk and invokes the callback when done', (done) => {
session.defaultSession.cookies.set({
url: url,
name: 'foo',
value: 'bar'
}, (error) => {
if (error) return done(error)
session.defaultSession.cookies.flushStore(() => done())
})
await cookies.set({ url, name, value })
await cookies.flushStore()
})
})
@ -304,26 +233,6 @@ describe('session module', () => {
})
w.loadFile(path.join(fixtures, 'api', 'localstorage.html'))
})
// TODO(codebytere): remove when promisification is complete
it('clears localstorage data (callback)', (done) => {
ipcMain.on('count', (event, count) => {
ipcMain.removeAllListeners('count')
assert.strictEqual(count, 0)
done()
})
w.webContents.on('did-finish-load', () => {
const options = {
origin: 'file://',
storages: ['localstorage'],
quotas: ['persistent']
}
w.webContents.session.clearStorageData(options, () => {
w.webContents.send('getcount')
})
})
w.loadFile(path.join(fixtures, 'api', 'localstorage.html'))
})
})
describe('will-download event', () => {
@ -627,17 +536,6 @@ describe('session module', () => {
assert.strictEqual(proxy, 'PROXY myproxy:80')
})
// TODO(codebytere): remove when Promisification is complete
it('allows configuring proxy settings (callback)', (done) => {
const config = { proxyRules: 'http=myproxy:80' }
customSession.setProxy(config, () => {
customSession.resolveProxy('http://example.com/', proxy => {
assert.strictEqual(proxy, 'PROXY myproxy:80')
done()
})
})
})
it('allows removing the implicit bypass rules for localhost', async () => {
const config = {
proxyRules: 'http=myproxy:80',
@ -649,20 +547,6 @@ describe('session module', () => {
assert.strictEqual(proxy, 'PROXY myproxy:80')
})
// TODO(codebytere): remove when Promisification is complete
it('allows removing the implicit bypass rules for localhost (callback)', (done) => {
const config = {
proxyRules: 'http=myproxy:80',
proxyBypassRules: '<-loopback>'
}
customSession.setProxy(config).then(() => {
customSession.resolveProxy('http://localhost').then(proxy => {
assert.strictEqual(proxy, 'PROXY myproxy:80')
done()
})
})
})
it('allows configuring proxy settings with pacScript', async () => {
server = http.createServer((req, res) => {
const pac = `
@ -690,30 +574,6 @@ describe('session module', () => {
})
})
// TODO(codebytere): reconfigure when Promisification is complete
it('allows configuring proxy settings with pacScript (callback)', (done) => {
server = http.createServer((req, res) => {
const pac = `
function FindProxyForURL(url, host) {
return "PROXY myproxy:8132";
}
`
res.writeHead(200, {
'Content-Type': 'application/x-ns-proxy-autoconfig'
})
res.end(pac)
})
server.listen(0, '127.0.0.1', () => {
const config = { pacScript: `http://127.0.0.1:${server.address().port}` }
customSession.setProxy(config, () => {
customSession.resolveProxy('https://google.com', proxy => {
assert.strictEqual(proxy, 'PROXY myproxy:8132')
done()
})
})
})
})
it('allows bypassing proxy settings', async () => {
const config = {
proxyRules: 'http=myproxy:80',
@ -723,20 +583,6 @@ describe('session module', () => {
const proxy = await customSession.resolveProxy('http://example/')
assert.strictEqual(proxy, 'DIRECT')
})
// TODO(codebytere): remove when Promisification is complete
it('allows bypassing proxy settings (callback)', (done) => {
const config = {
proxyRules: 'http=myproxy:80',
proxyBypassRules: '<local>'
}
customSession.setProxy(config, () => {
customSession.resolveProxy('http://example/', proxy => {
assert.strictEqual(proxy, 'DIRECT')
done()
})
})
})
})
describe('ses.getBlobData()', () => {
@ -982,59 +828,6 @@ describe('session module', () => {
issueLoginRequest()
})
})
// TODO(codebytere): remove when promisification complete
it('can clear http auth info from cache (callback)', (done) => {
const ses = session.fromPartition('auth-cache')
const server = http.createServer((req, res) => {
const credentials = auth(req)
if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') {
res.statusCode = 401
res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"')
res.end()
} else {
res.end('authenticated')
}
})
server.listen(0, '127.0.0.1', () => {
const port = server.address().port
function issueLoginRequest (attempt = 1) {
if (attempt > 2) {
server.close()
return done()
}
const request = net.request({
url: `http://127.0.0.1:${port}`,
session: ses
})
request.on('login', (info, callback) => {
attempt += 1
assert.strictEqual(info.scheme, 'basic')
assert.strictEqual(info.realm, 'Restricted')
callback('test', 'test')
})
request.on('response', (response) => {
let data = ''
response.pause()
response.on('data', (chunk) => {
data += chunk
})
response.on('end', () => {
assert.strictEqual(data, 'authenticated')
ses.clearAuthCache({ type: 'password' }, () => {
issueLoginRequest(attempt)
})
})
response.on('error', (error) => { done(error) })
response.resume()
})
// Internal api to bypass cache for testing.
request.urlRequest._setLoadFlags(1 << 1)
request.end()
}
issueLoginRequest()
})
})
})
describe('ses.setPermissionRequestHandler(handler)', () => {

View file

@ -85,20 +85,17 @@ describe('renderer nodeIntegrationInSubFrames', () => {
w.loadFile(path.resolve(__dirname, `fixtures/sub-frames/frame-container${fixtureSuffix}.html`))
const details = await detailsPromise
const senders = details.map(event => event[0].sender)
await new Promise((resolve) => {
await new Promise(async resolve => {
let resultCount = 0
senders.forEach(sender => {
sender.webContents.executeJavaScript('window.isolatedGlobal', result => {
if (webPreferences.contextIsolation) {
expect(result).to.be.null()
} else {
expect(result).to.equal(true)
}
resultCount++
if (resultCount === senders.length) {
resolve()
}
})
senders.forEach(async sender => {
const result = await sender.webContents.executeJavaScript('window.isolatedGlobal')
if (webPreferences.contextIsolation) {
expect(result).to.be.null()
} else {
expect(result).to.equal(true)
}
resultCount++
if (resultCount === senders.length) resolve()
})
})
})

View file

@ -184,18 +184,16 @@ describe('webContents module', () => {
})
describe('setDevToolsWebContents() API', () => {
it('sets arbitry webContents as devtools', (done) => {
it('sets arbitrary webContents as devtools', async () => {
const devtools = new BrowserWindow({ show: false })
devtools.webContents.once('dom-ready', () => {
assert.ok(devtools.getURL().startsWith('chrome-devtools://devtools'))
devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name', (name) => {
assert.ok(name, 'InspectorFrontendHostImpl')
devtools.destroy()
done()
})
})
const promise = emittedOnce(devtools.webContents, 'dom-ready')
w.webContents.setDevToolsWebContents(devtools.webContents)
w.webContents.openDevTools()
await promise
expect(devtools.getURL().startsWith('chrome-devtools://devtools')).to.be.true()
const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name')
expect(result).to.equal('InspectorFrontendHostImpl')
devtools.destroy()
})
})
@ -478,20 +476,16 @@ describe('webContents module', () => {
})
})
it('supports inserting CSS', (done) => {
it('supports inserting CSS', async () => {
w.loadURL('about:blank')
w.webContents.insertCSS('body { background-repeat: round; }')
w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")', (result) => {
assert.strictEqual(result, 'round')
done()
})
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")')
expect(result).to.equal('round')
})
it('supports inspecting an element in the devtools', (done) => {
w.loadURL('about:blank')
w.webContents.once('devtools-opened', () => {
done()
})
w.webContents.once('devtools-opened', () => { done() })
w.webContents.inspectElement(10, 10)
})
@ -578,20 +572,6 @@ describe('webContents module', () => {
}
})
// TODO(codebytere): remove when promisification is complete
it('can set the correct zoom level (callback)', async () => {
try {
await w.loadURL('about:blank')
const zoomLevel = await new Promise(resolve => w.webContents.getZoomLevel(resolve))
expect(zoomLevel).to.eql(0.0)
w.webContents.setZoomLevel(0.5)
const newZoomLevel = await new Promise(resolve => w.webContents.getZoomLevel(resolve))
expect(newZoomLevel).to.eql(0.5)
} finally {
w.webContents.setZoomLevel(0)
}
})
it('can persist zoom level across navigation', (done) => {
let finalNavigation = false
ipcMain.on('set-zoom', (e, host) => {
@ -732,7 +712,7 @@ describe('webContents module', () => {
`
w.webContents.on('did-finish-load', () => {
if (initialNavigation) {
w.webContents.executeJavaScript(source, () => {})
w.webContents.executeJavaScript(source)
} else {
const zoomLevel = w.webContents.getZoomLevel()
assert.strictEqual(zoomLevel, 0)
@ -1066,24 +1046,6 @@ describe('webContents module', () => {
const result = await w.webContents.executeJavaScript('37 + 5')
assert.strictEqual(result, 42)
})
// TODO(miniak): remove when promisification is complete
it('responds to executeJavaScript (callback)', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
})
w.webContents.once('did-finish-load', () => {
w.webContents.executeJavaScript('37 + 5', (result) => {
assert.strictEqual(result, 42)
done()
})
})
w.loadURL('about:blank')
})
})
describe('preload-error event', () => {
@ -1306,25 +1268,5 @@ describe('webContents module', () => {
assert.strictEqual(data instanceof Buffer, true)
assert.notStrictEqual(data.length, 0)
})
// TODO(miniak): remove when promisification is complete
it('can print to PDF (callback)', (done) => {
w.destroy()
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
})
w.webContents.once('did-finish-load', () => {
w.webContents.printToPDF({}, function (error, data) {
assert.strictEqual(error, null)
assert.strictEqual(data instanceof Buffer, true)
assert.notStrictEqual(data.length, 0)
done()
})
})
w.loadURL('data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E')
})
})
})

View file

@ -1347,11 +1347,11 @@ describe('chromium feature', () => {
describe('window.history.pushState', () => {
it('should push state after calling history.pushState() from the same url', (done) => {
w = new BrowserWindow({ show: false })
w.webContents.once('did-finish-load', () => {
w.webContents.once('did-finish-load', async () => {
// History should have current page by now.
assert.strictEqual(w.webContents.length(), 1)
w.webContents.executeJavaScript('window.history.pushState({}, "")', () => {
w.webContents.executeJavaScript('window.history.pushState({}, "")').then(() => {
// Initial page + pushed state
assert.strictEqual(w.webContents.length(), 2)
done()

View file

@ -52,33 +52,27 @@ describe('chrome extension content scripts', () => {
return closeWindow(w).then(() => { w = null })
})
it('should run content script at document_start', (done) => {
it('should run content script at document_start', () => {
addExtension('content-script-document-start')
w.webContents.once('dom-ready', () => {
w.webContents.executeJavaScript('document.documentElement.style.backgroundColor', (result) => {
expect(result).to.equal('red')
done()
})
w.webContents.once('dom-ready', async () => {
const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor')
expect(result).to.equal('red')
})
w.loadURL('about:blank')
})
it('should run content script at document_idle', (done) => {
it('should run content script at document_idle', async () => {
addExtension('content-script-document-idle')
w.loadURL('about:blank')
w.webContents.executeJavaScript('document.body.style.backgroundColor', (result) => {
expect(result).to.equal('red')
done()
})
const result = await w.webContents.executeJavaScript('document.body.style.backgroundColor')
expect(result).to.equal('red')
})
it('should run content script at document_end', (done) => {
it('should run content script at document_end', () => {
addExtension('content-script-document-end')
w.webContents.once('did-finish-load', () => {
w.webContents.executeJavaScript('document.documentElement.style.backgroundColor', (result) => {
expect(result).to.equal('red')
done()
})
w.webContents.once('did-finish-load', async () => {
const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor')
expect(result).to.equal('red')
})
w.loadURL('about:blank')
})

View file

@ -7,7 +7,7 @@ if (process.isMainFrame) {
if (!frame) {
throw new Error(`Can't find frame for routing ID ${frameRoutingId}`)
}
frame.executeJavaScript(code, false, result => {
frame.executeJavaScript(code, false).then(result => {
event.sender.send(`executeJavaScriptInFrame_${responseId}`, result)
})
})

View file

@ -217,18 +217,8 @@ app.on('ready', function () {
event.returnValue = null
})
ipcMain.on('executeJavaScript', function (event, code, hasCallback) {
let promise
if (hasCallback) {
promise = window.webContents.executeJavaScript(code, (result) => {
window.webContents.send('executeJavaScript-response', result)
})
} else {
promise = window.webContents.executeJavaScript(code)
}
promise.then((result) => {
ipcMain.on('executeJavaScript', function (event, code) {
window.webContents.executeJavaScript(code).then((result) => {
window.webContents.send('executeJavaScript-promise-response', result)
}).catch((error) => {
window.webContents.send('executeJavaScript-promise-error', error)
@ -237,10 +227,6 @@ app.on('ready', function () {
window.webContents.send('executeJavaScript-promise-error-name', error.name)
}
})
if (!hasCallback) {
event.returnValue = 'success'
}
})
})

View file

@ -92,14 +92,14 @@ app.on('ready', () => {
printBackground: true,
printSelectionOnly: true,
landscape: true
}, (error: Error, data: Buffer) => console.log(error))
}).then((data: Buffer) => console.log(data))
mainWindow.webContents.printToPDF({}, (err, data) => console.log(err))
mainWindow.webContents.printToPDF({}).then(data => console.log(data))
mainWindow.webContents.executeJavaScript('return true;').then((v: boolean) => console.log(v))
mainWindow.webContents.executeJavaScript('return true;', true).then((v: boolean) => console.log(v))
mainWindow.webContents.executeJavaScript('return true;', true)
mainWindow.webContents.executeJavaScript('return true;', true, (result: boolean) => console.log(result))
mainWindow.webContents.executeJavaScript('return true;', true).then((result: boolean) => console.log(result))
mainWindow.webContents.insertText('blah, blah, blah')
mainWindow.webContents.startDrag({ file: '/path/to/img.png', icon: nativeImage.createFromPath('/path/to/icon.png') })
mainWindow.webContents.findInPage('blah')
@ -138,10 +138,10 @@ app.on('ready', () => {
})
mainWindow.webContents.debugger.sendCommand('Network.enable')
mainWindow.webContents.capturePage((image) => {
mainWindow.webContents.capturePage().then(image => {
console.log(image.toDataURL())
})
mainWindow.webContents.capturePage({ x: 0, y: 0, width: 100, height: 200 }, (image) => {
mainWindow.webContents.capturePage({ x: 0, y: 0, width: 100, height: 200 }).then(image => {
console.log(image.toPNG())
})
})
@ -467,11 +467,11 @@ const options = {
traceOptions: 'record-until-full,enable-sampling'
}
contentTracing.startRecording(options, function () {
contentTracing.startRecording(options).then(() => {
console.log('Tracing started')
setTimeout(function () {
contentTracing.stopRecording('', function (path) {
console.log('Tracing data recorded to ' + path)
contentTracing.stopRecording('').then(path => {
console.log(`Tracing data recorded to ${path}`)
})
}, 5000)
})
@ -850,7 +850,7 @@ app.on('ready', () => {
console.log(error ? error.message : 'ok')
})
protocol.isProtocolHandled('atom', (handled) => {
protocol.isProtocolHandled('atom').then(handled => {
console.log(handled)
})
})

View file

@ -5,7 +5,6 @@ import {
webFrame,
clipboard,
crashReporter,
nativeImage,
screen,
shell
} from 'electron'
@ -34,7 +33,7 @@ remote.getCurrentWindow().on('close', () => {
// blabla...
})
remote.getCurrentWindow().capturePage(buf => {
remote.getCurrentWindow().capturePage().then(buf => {
fs.writeFile('/tmp/screenshot.png', buf, err => {
console.log(err)
})
@ -42,7 +41,7 @@ remote.getCurrentWindow().capturePage(buf => {
remote.getCurrentWebContents().print()
remote.getCurrentWindow().capturePage(buf => {
remote.getCurrentWindow().capturePage().then(buf => {
remote.require('fs').writeFile('/tmp/screenshot.png', buf, (err: Error) => {
console.log(err)
})
@ -75,7 +74,7 @@ webFrame.insertText('text')
webFrame.executeJavaScript('return true;').then((v: boolean) => console.log(v))
webFrame.executeJavaScript('return true;', true).then((v: boolean) => console.log(v))
webFrame.executeJavaScript('return true;', true)
webFrame.executeJavaScript('return true;', true, (result: boolean) => console.log(result))
webFrame.executeJavaScript('return true;', true).then((result: boolean) => console.log(result))
console.log(webFrame.getResourceUsage())
webFrame.clearCache()
@ -111,8 +110,7 @@ crashReporter.start({
const desktopCapturer = require('electron').desktopCapturer
desktopCapturer.getSources({ types: ['window', 'screen'] }, function (error, sources) {
if (error) throw error
desktopCapturer.getSources({ types: ['window', 'screen'] }).then(sources => {
for (let i = 0; i < sources.length; ++i) {
if (sources[i].name == 'Electron') {
(navigator as any).webkitGetUserMedia({
@ -253,7 +251,7 @@ webview.addEventListener('ipc-message', function (event) {
console.log(event.channel) // Prints "pong"
})
webview.send('ping')
webview.capturePage((image) => { console.log(image) })
webview.capturePage().then(image => { console.log(image) })
{
const opened: boolean = webview.isDevToolsOpened()

View file

@ -1000,23 +1000,6 @@ describe('<webview> tag', function () {
const result = await webview.executeJavaScript(jsScript)
assert.strictEqual(result, expectedResult)
})
// TODO(miniak): remove when promisification is complete
it('can return the result of the executed script (callback)', async () => {
await loadWebView(webview, {
src: 'about:blank'
})
const jsScript = "'4'+2"
const expectedResult = '42'
const result = await new Promise((resolve) => {
webview.executeJavaScript(jsScript, false, (result) => {
resolve(result)
})
})
assert.strictEqual(result, expectedResult)
})
})
describe('sendInputEvent', () => {
@ -1272,21 +1255,6 @@ describe('<webview> tag', function () {
assert.strictEqual(data instanceof Buffer, true)
assert.notStrictEqual(data.length, 0)
})
// TODO(miniak): remove when promisification is complete
it('can print to PDF (callback)', (done) => {
webview.addEventListener('did-finish-load', () => {
webview.printToPDF({}, function (error, data) {
assert.strictEqual(error, null)
assert.strictEqual(data instanceof Buffer, true)
assert.notStrictEqual(data.length, 0)
done()
})
})
webview.src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'
document.body.appendChild(webview)
})
})
// FIXME(deepak1556): Ch69 follow up.