Implement chrome.runtime.sendMessage

This commit is contained in:
Cheng Zhao 2016-05-28 21:23:43 +09:00
parent ba315248e0
commit 62fb4f9820
2 changed files with 42 additions and 2 deletions

View file

@ -86,6 +86,16 @@ ipcMain.on('CHROME_RUNTIME_CONNECT', function (event, extensionId, connectInfo)
page.webContents.sendToAll('CHROME_RUNTIME_ONCONNECT', event.sender.id, portId, extensionId, connectInfo)
})
ipcMain.on('CHROME_RUNTIME_SENDMESSAGE', function (event, extensionId, message) {
const page = backgroundPages[extensionId]
if (!page) {
console.error(`Connect to unkown extension ${extensionId}`)
return
}
page.webContents.sendToAll('CHROME_RUNTIME_ONMESSAGE', message)
})
ipcMain.on('CHROME_TABS_EXECUTESCRIPT', function (event, requestId, webContentsId, extensionId, details) {
const contents = webContents.fromId(webContentsId)
if (!contents) {

View file

@ -88,6 +88,16 @@ class OnConnect extends Event {
}
}
class OnMessage extends Event {
constructor () {
super()
ipcRenderer.on('CHROME_RUNTIME_ONMESSAGE', (event, message) => {
this.emit(message)
})
}
}
// Inject chrome API to the |context|
exports.injectTo = function (extensionId, context) {
const chrome = context.chrome = context.chrome || {}
@ -116,7 +126,25 @@ exports.injectTo = function (extensionId, context) {
const {webContentsId, portId} = ipcRenderer.sendSync('CHROME_RUNTIME_CONNECT', targetExtensionId, connectInfo)
return new Port(webContentsId, portId, extensionId, connectInfo.name)
}
},
sendMessage (...args) {
// Parse the optional args.
let targetExtensionId = extensionId
let message, options, responseCallback
if (args.length === 1) {
message = args[0]
} else if (args.length === 2) {
[targetExtensionId, message] = args
} else {
console.error('responseCallback is not supported')
[targetExtensionId, message, options, responseCallback] = args
}
ipcRenderer.send('CHROME_RUNTIME_SENDMESSAGE', targetExtensionId, message)
},
onMessage: new OnMessage()
}
chrome.tabs = {
@ -132,7 +160,9 @@ exports.injectTo = function (extensionId, context) {
chrome.extension = {
getURL: chrome.runtime.getURL,
connect: chrome.runtime.connect,
onConnect: chrome.runtime.onConnect
onConnect: chrome.runtime.onConnect,
sendMessage: chrome.runtime.sendMessage,
onMessage: chrome.runtime.onMessage
}
chrome.storage = {