sending message to chrome extension from a web page

前端 未结 5 541
遇见更好的自我
遇见更好的自我 2020-11-27 13:24

I want to send message from the console of the random web page to my chrome extension. chrome.extension.sendMessage doesn\'t seem to work.

5条回答
  •  隐瞒了意图╮
    2020-11-27 14:05

    Here's a quote from the latest http://developer.chrome.com/extensions/messaging.html, It's much simpler to support this kind of feature now, here's how:

    Sending messages from web pages

    Similar to cross-extension messaging, your app or extension can receive and respond to messages from regular web pages. To use this feature, you must first specify in your manifest.json which web sites you want to communicate with. For example:

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

    This will expose the messaging API to any page which matches the URL patterns you specify. The URL pattern must contain at least a second-level domain - that is, hostname patterns like "", ".com", ".co.uk", and ".appspot.com" and are prohibited. From the web page, use the runtime.sendMessage or runtime.connect APIs to send a message to a specific app or extension. For example:

    // The ID of the extension we want to talk to.
    var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";
    
    // Make a simple request:
    chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
      function(response) {
        if (!response.success)
          handleError(url);
      });
    

    From your app or extension, you may listen to messages from web pages via the runtime.onMessageExternal or runtime.onConnectExternal APIs, similar to cross-extension messaging. Only the web page can initiate a connection. Here is an example:

    chrome.runtime.onMessageExternal.addListener(
      function(request, sender, sendResponse) {
        if (sender.url == blacklistedWebsite)
          return;  // don't allow this web page access
        if (request.openUrlInEditor)
          openUrl(request.openUrlInEditor);
      });
    

提交回复
热议问题