Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add ipcRenderer.invoke() #18449

Merged
merged 7 commits into from
May 31, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add tentative handle() api and spec
  • Loading branch information
nornagon committed May 29, 2019
commit 1a7f77f234b8198e7bf143c4e8a248e6dfd37bb7
1 change: 1 addition & 0 deletions docs/api/structures/ipc-main-event.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@
* `sender` WebContents - Returns the `webContents` that sent the message
* `reply` Function - A function that will send an IPC message to the renderer frame that sent the original message that you are currently handling. You should use this method to "reply" to the sent message in order to guaruntee the reply will go to the correct process and frame.
nornagon marked this conversation as resolved.
Show resolved Hide resolved
* `...args` any[]
* `throw` Function - (only for 'invoke' events) Reject the waiting promise on the caller's end with the given string
IpcRenderer
21 changes: 18 additions & 3 deletions lib/browser/api/ipc-main.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
import { EventEmitter } from 'events'

const emitter = new EventEmitter()
class IpcMain extends EventEmitter {
nornagon marked this conversation as resolved.
Show resolved Hide resolved
handle (method: string, fn: Function) {
if (this.listenerCount(method) !== 0) {
throw new Error(`Attempted to register a second handler for '${method}'`)
}
this.on(method, async (e, ...args) => {
try {
e.reply(await Promise.resolve(fn(...args)))
} catch (err) {
e.throw(err)
}
})
}
}

const ipcMain = new IpcMain()

// Do not throw exception when channel name is "error".
emitter.on('error', () => {})
ipcMain.on('error', () => {})

export default emitter
export default ipcMain
3 changes: 2 additions & 1 deletion lib/browser/api/web-contents.js
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,8 @@ WebContents.prototype._init = function () {
})

this.on('-ipc-invoke', function (event, channel, args) {
event.reply = event.sendReply
event.reply = (result) => event.sendReply({ result })
event.throw = (error) => event.sendReply({ error: error.toString() })
nornagon marked this conversation as resolved.
Show resolved Hide resolved
this.emit('ipc-invoke', event, channel, ...args)
nornagon marked this conversation as resolved.
Show resolved Hide resolved
ipcMain.emit(channel, event, ...args)
})
Expand Down
5 changes: 4 additions & 1 deletion lib/renderer/api/ipc-renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ ipcRenderer.sendToAll = function (webContentsId, channel, ...args) {
}

ipcRenderer.invoke = function (channel, ...args) {
return ipc.invoke(channel, args)
return ipc.invoke(channel, args).then(({ error, result }) => {
if (error) { throw new Error(`Error invoking remote method '${channel}': ${error}`) }
nornagon marked this conversation as resolved.
Show resolved Hide resolved
return result
})
}

module.exports = ipcRenderer
136 changes: 136 additions & 0 deletions spec-main/api-ipc-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import * as chai from 'chai'
import * as chaiAsPromised from 'chai-as-promised'
import { BrowserWindow, ipcMain } from 'electron'

const { expect } = chai

chai.use(chaiAsPromised)

describe('ipc module', () => {
describe('invoke', () => {
async function rendererInvoke(...args: any[]) {
const {ipcRenderer} = require('electron')
try {
const result = await ipcRenderer.invoke('test', ...args)
ipcRenderer.send('result', {result})
} catch (e) {
ipcRenderer.send('result', {error: e.message})
}
}

it('receives responses', async () => {
ipcMain.once('test', (e, arg) => {
expect(arg).to.equal(123)
e.reply('456')
})
const done = new Promise(resolve => {
ipcMain.once('result', (e, arg) => {
expect(arg).to.deep.equal({result: '456'})
resolve()
})
})
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } })
try {
await w.loadURL(`data:text/html,<script>(${rendererInvoke})(123)</script>`)
await done
} finally {
w.destroy()
}
})

it('receives errors', async () => {
ipcMain.once('test', (e) => {
e.throw('some error')
})
const done = new Promise(resolve => {
ipcMain.once('result', (e, arg) => {
expect(arg.error).to.match(/some error/)
resolve()
})
})
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } })
try {
await w.loadURL(`data:text/html,<script>(${rendererInvoke})()</script>`)
await done
} finally {
w.destroy()
}
})

it('registers a synchronous handler', async () => {
(ipcMain as any).handle('test', (arg: number) => {
ipcMain.removeAllListeners('test')
expect(arg).to.equal(123)
return 3
})
const done = new Promise(resolve => ipcMain.once('result', (e, arg) => {
expect(arg).to.deep.equal({result: 3})
resolve()
}))
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } })
try {
await w.loadURL(`data:text/html,<script>(${rendererInvoke})(123)</script>`)
await done
} finally {
w.destroy()
}
})

it('registers an asynchronous handler', async () => {
(ipcMain as any).handle('test', async (arg: number) => {
ipcMain.removeAllListeners('test')
expect(arg).to.equal(123)
await new Promise(resolve => setImmediate(resolve))
return 3
})
const done = new Promise(resolve => ipcMain.once('result', (e, arg) => {
expect(arg).to.deep.equal({result: 3})
resolve()
}))
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } })
try {
await w.loadURL(`data:text/html,<script>(${rendererInvoke})(123)</script>`)
await done
} finally {
w.destroy()
}
})

it('receives an error from a synchronous handler', async () => {
(ipcMain as any).handle('test', () => {
ipcMain.removeAllListeners('test')
throw new Error('some error')
})
const done = new Promise(resolve => ipcMain.once('result', (e, arg) => {
expect(arg.error).to.match(/some error/)
resolve()
}))
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } })
try {
await w.loadURL(`data:text/html,<script>(${rendererInvoke})()</script>`)
await done
} finally {
w.destroy()
}
})

it('receives an error from an asynchronous handler', async () => {
(ipcMain as any).handle('test', async () => {
ipcMain.removeAllListeners('test')
await new Promise(resolve => setImmediate(resolve))
throw new Error('some error')
})
const done = new Promise(resolve => ipcMain.once('result', (e, arg) => {
expect(arg.error).to.match(/some error/)
resolve()
}))
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } })
try {
await w.loadURL(`data:text/html,<script>(${rendererInvoke})()</script>`)
await done
} finally {
w.destroy()
}
})
})
})