简体   繁体   中英

Message passing from external webpage to chrome addon

I am trying to make a webpage send data to a chrome extension that will fire when user visit a website(say google here)

manifest.json

{
  "manifest_version": 2,
  "name": "Test Addon",
  "version": "0.01",
  "icons": { "16": "icon-16.ico" },

  "browser_action": {
  "default_icon" : "icon-16.ico",
  "default_popup" : "popup.html"
  },

   "content_scripts": [
    {
      "matches": ["*://*.google.com/*"  ],
      "js": ["cs.js"]
    }
  ],

  "externally_connectable": {
  "matches": ["*://*.mywebsite.com/*"]
}


}

cs.js

chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    alert("world");
  });

mywebsite.com/testpage.php

// The ID of my chrome extension (In developer mode)
var editorExtensionId = "cjgeckgdpfhnedenpkaanpehddchlkle";

// Send a message
chrome.runtime.sendMessage("Hello");

</script>

As far as i know content script have access to onMessage and sendMessage but i don't get an alert when i visit google

According to the docs , the extension id should be the first parameter when calling sendMessage() . You simply omitted this param.
The second problem is that messages from external web page can receive only the background script. Check the docs for onMessageExternal() .
Use this code to send a message to your background extension script:

// The ID of my chrome extension (In developer mode)
var editorExtensionId = "cjgeckgdpfhnedenpkaanpehddchlkle";

// Send a message
chrome.runtime.sendMessage(editorExtensionId, "Hello");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM