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.
@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
});
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.
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);
});
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.