Handle port disconnecting

This commit is contained in:
Cheng Zhao 2016-05-28 12:07:08 +09:00
parent 599d3c147b
commit d8db695712
3 changed files with 42 additions and 16 deletions

View file

@ -78,6 +78,8 @@ const removeBackgroundPages = function (manifest) {
}
// Handle the chrome.* API messages.
let nextId = 0
ipcMain.on('CHROME_RUNTIME_CONNECT', function (event, hostname, connectInfo) {
const page = backgroundPages[hostname]
if (!page) {
@ -85,18 +87,33 @@ ipcMain.on('CHROME_RUNTIME_CONNECT', function (event, hostname, connectInfo) {
return
}
event.returnValue = page.webContents.id
page.webContents.sendToAll('CHROME_RUNTIME_ONCONNECT', event.sender.id, hostname, connectInfo)
const portId = ++nextId
event.returnValue = {webContentsId: page.webContents.id, portId: portId}
event.sender.once('render-view-deleted', () => {
page.webContents.sendToAll(`CHROME_PORT_ONDISCONNECT_${portId}`)
})
page.webContents.sendToAll('CHROME_RUNTIME_ONCONNECT', event.sender.id, portId, connectInfo)
})
ipcMain.on('CHROME_PORT_POSTMESSAGE', function (event, webContentsId, hostname, message) {
ipcMain.on('CHROME_PORT_DISCONNECT', function (event, webContentsId, portId) {
const contents = webContents.fromId(webContentsId)
if (!contents) {
console.error(`Sending message to extension ${hostname} with unkown webContentsId ${webContentsId}`)
console.error(`Disconnet to unkown webContentsId ${webContentsId}`)
return
}
contents.sendToAll(`CHROME_PORT_ONMESSAGE_${hostname}`, message)
contents.sendToAll(`CHROME_PORT_ONDISCONNECT_${portId}`)
})
ipcMain.on('CHROME_PORT_POSTMESSAGE', function (event, webContentsId, portId, message) {
const contents = webContents.fromId(webContentsId)
if (!contents) {
console.error(`Sending message to unkown webContentsId ${webContentsId}`)
return
}
contents.sendToAll(`CHROME_PORT_ONMESSAGE_${portId}`, message)
})
// Transfer the content scripts to renderer.