Implement chrome.runtime.sendMessage
authorCheng Zhao <zcbenz@gmail.com>
Sat, 28 May 2016 12:23:43 +0000 (21:23 +0900)
committerCheng Zhao <zcbenz@gmail.com>
Sat, 28 May 2016 12:23:43 +0000 (21:23 +0900)
lib/browser/chrome-extension.js
lib/renderer/chrome-api.js

index ad8af72..57c40dd 100644 (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) {
index 646e5bd..1e9f549 100644 (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 = {