Make executeJavaScript return a Promise so that caught errors can be sent to the caller

This commit is contained in:
Samuel Attard 2016-10-11 16:47:09 +11:00 committed by Kevin Sawicki
parent 75b010ce63
commit 857e1da6a3
5 changed files with 59 additions and 7 deletions

View file

@ -110,9 +110,15 @@ const webFrameMethodsWithResult = [
]
const asyncWebFrameMethods = function (requestId, method, callback, ...args) {
this.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', requestId, method, args)
ipcMain.once(`ELECTRON_INTERNAL_BROWSER_ASYNC_WEB_FRAME_RESPONSE_${requestId}`, function (event, result) {
if (callback) callback(result)
return new Promise((resolve, reject) => {
this.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', requestId, method, args)
ipcMain.once(`ELECTRON_INTERNAL_BROWSER_ASYNC_WEB_FRAME_RESPONSE_${requestId}`, function (event, result) {
if (callback) callback(result)
resolve(result)
})
ipcMain.once(`ELECTRON_INTERNAL_BROWSER_ASYNC_WEB_FRAME_ERROR_${requestId}`, (event, error) => {
reject(error)
})
})
}
@ -146,10 +152,12 @@ WebContents.prototype.executeJavaScript = function (code, hasUserGesture, callba
hasUserGesture = false
}
if (this.getURL() && !this.isLoadingMainFrame()) {
asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture)
return asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture)
} else {
this.once('did-finish-load', () => {
asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture)
return new Promise((resolve, reject) => {
this.once('did-finish-load', () => {
asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', callback, code, hasUserGesture).then(resolve).catch(reject)
})
})
}
}