sendMessage from extension background or popup to content script doesn't work

后端 未结 4 949
孤街浪徒
孤街浪徒 2020-12-02 05:38

I know that question has been repeatedly asked in different ways, but I tried to go through all the answers (hopefully I didn\'t miss anyone) and none of them worked for me.

相关标签:
4条回答
  • 2020-12-02 06:14

    @apsillers is correct. Also don't forget to return true in your content-script listener or it might close too early.

    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
        console.log(message)
        return true
    });
    
    0 讨论(0)
  • 2020-12-02 06:25

    My use-case required sending a message to the background script from a webpage. I used chrome.runtime.onMessageExternal to catch this message.

    Inside of this listener I was basically forwarding the message over to my content script so it could do its thing, but I could not figure out why my content script onMessage listener wouldn't catch the message.

    Turns out by waiting for 1 second before sending the message from the webpage (I was basically doing it on load) I was able to see the message hitting my content script.

    0 讨论(0)
  • 2020-12-02 06:26

    Here's an example of a background script that sends a message to the content-script file.

    background.js

    chrome.tabs.sendMessage(tabs[0].id,"your message"); 
    

    content-script/content.js

    chrome.runtime.onMessage.addListener(function (response, sendResponse) {
              console.log(response);
    });
    
    0 讨论(0)
  • 2020-12-02 06:29

    In your background page you should call

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        chrome.tabs.sendMessage(tabs[0].id, {action: "open_dialog_box"}, function(response) {});  
    });
    

    instead of using chrome.extension.sendMessage as you currently do.

    The chrome.tabs variant sends messages to content scripts, whereas the chrome.extension function sends messages to all other extension components.

    0 讨论(0)
提交回复
热议问题