sending message to chrome extension from a web page

前端 未结 5 524
遇见更好的自我
遇见更好的自我 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 13:55

    So to elaborate, a more concreate example: An issue with chrome.runtime.sendMessage(...) style is that you have to specify the pag you're on as externally_connectable which doesn't take a global wildcard like "https:///". So if you want that ability, you have to use the postMessage style communication. Capture the message from the window into the contentscript, then from the contentscript, you can send it elsewhere (if desired, like to the background.js etc.)

    So in the normal web page, or in injected source that you embed into the normal page, from your contentscript.js, send a message like this:

    window.postMessage({ type: "FROM_PAGE_TO_CONTENT_SCRIPT", 
         text: "Hello from the webpage!" }, "*");
    

    ex, you could add it to a button like this:

    document.getElementById("theButton").addEventListener("click",
        function() {
           window.postMessage({ type: "FROM_PAGE_TO_CONTENT_SCRIPT", 
                                text: "Hello from the webpage!" }, "*");
    }, false);
    

    Then to capture it in the contentscript.js and "send it on" to the rest of the extension, the only caveat is that you only want to "select" messages that seem to be ones that you care about:

    window.addEventListener("message", function(event) {
      // We only accept messages from this window to itself [i.e. not from any iframes]
      if (event.source != window)
        return;
    
      if (event.data.type && (event.data.type == "FROM_PAGE_TO_CONTENT_SCRIPT")) {        
        chrome.runtime.sendMessage(event.data); // broadcasts it to rest of extension, or could just broadcast event.data.payload...
      } // else ignore messages seemingly not sent to yourself
    }, false);
    

提交回复
热议问题