Implement chrome.runtime.onMessage response callback

This commit is contained in:
Samuel Attard 2016-11-15 21:30:40 +11:00
parent 7cfe1dd0af
commit 01005688b6
No known key found for this signature in database
GPG key ID: 273DC1869D8F13EF
2 changed files with 26 additions and 11 deletions

View file

@ -59,13 +59,16 @@ class Port {
// Inject chrome API to the |context|
exports.injectTo = function (extensionId, isBackgroundPage, context) {
const chrome = context.chrome = context.chrome || {}
let originResultID = 1
ipcRenderer.on(`CHROME_RUNTIME_ONCONNECT_${extensionId}`, (event, tabId, portId, connectInfo) => {
chrome.runtime.onConnect.emit(new Port(tabId, portId, extensionId, connectInfo.name))
})
ipcRenderer.on(`CHROME_RUNTIME_ONMESSAGE_${extensionId}`, (event, tabId, message) => {
chrome.runtime.onMessage.emit(message, new MessageSender(tabId, extensionId))
ipcRenderer.on(`CHROME_RUNTIME_ONMESSAGE_${extensionId}`, (event, tabId, message, resultID) => {
chrome.runtime.onMessage.emit(message, new MessageSender(tabId, extensionId), (messageResult) => {
ipcRenderer.send(`CHROME_RUNTIME_ONMESSAGE_RESULT_${resultID}`, messageResult)
})
})
ipcRenderer.on('CHROME_TABS_ONCREATED', (event, tabId) => {
@ -121,16 +124,18 @@ exports.injectTo = function (extensionId, isBackgroundPage, context) {
} else if (args.length === 2) {
// A case of not provide extension-id: (message, responseCallback)
if (typeof args[1] === 'function') {
console.error('responseCallback is not supported')
ipcRenderer.on(`CHROME_RUNTIME_SENDMESSAGE_RESULT_${originResultID}`, (event, result) => args[1](result))
message = args[0]
} else {
[targetExtensionId, message] = args
}
} else {
console.error('options and responseCallback are not supported')
console.error('options is not supported')
ipcRenderer.on(`CHROME_RUNTIME_SENDMESSAGE_RESULT_${originResultID}`, (event, result) => args[2](result))
}
ipcRenderer.send('CHROME_RUNTIME_SENDMESSAGE', targetExtensionId, message)
ipcRenderer.send('CHROME_RUNTIME_SENDMESSAGE', targetExtensionId, message, originResultID)
originResultID++
},
onConnect: new Event(),
@ -149,9 +154,10 @@ exports.injectTo = function (extensionId, isBackgroundPage, context) {
sendMessage (tabId, message, options, responseCallback) {
if (responseCallback) {
console.error('responseCallback is not supported')
ipcRenderer.on(`CHROME_TABS_SEND_MESSAGE_RESULT_${originResultID}`, (event, result) => responseCallback(result))
}
ipcRenderer.send('CHROME_TABS_SEND_MESSAGE', tabId, extensionId, isBackgroundPage, message)
ipcRenderer.send('CHROME_TABS_SEND_MESSAGE', tabId, extensionId, isBackgroundPage, message, originResultID)
originResultID++;
},
onUpdated: new Event(),