Reputation: 5714
I'm trying to get basic message passing to work in a Chrome extension. There are a number of related questions on SF on this (most notably here: Basic google chrome extension message passing not working), but unfortunately the advice there seems not to work for me.
Here's my manifest.json file:
{
"name": "Steve Screenshot",
"description": "Do something",
"version": "0.1",
"manifest_version": 2,
"content_scripts": [
{
"matches" : ["*://*/*"],
"js": ["simple.js"]
}
]
}
And my simple.js file:
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
console.log('message received');
});
// Invoke it!!!
chrome.runtime.sendMessage({
msg: 'whatever'
}, function(response) {
console.log('message sent');
});
At runtime, the console log shows the "message sent" message but NOT the "message received" message. To the best of my understanding, I am ?correctly? invoking chrome.runtime.onMessage/sendMessage. Can anyone comment?
Thanks, --Steve
Upvotes: 1
Views: 909
Reputation: 1960
The problem is that you are trying to use chrome.runtime.sendMessage
to send a message to a content script. You cannot send messages to content scripts using runtime.sendMessage
, you must use tabs.sendMessage
. (Read about that here).
A good setup for message passing is to use a background page as sort of a 'router' for your messages. When you need to pass a message to content scripts you do so from the background page using the tabs api. For a simple test, you could add a tabs.query
call in the background script to send a message to ALL content scripts like so:
chrome.tabs.query({}, function(tabs) {
for(var i = 0; i < tabs.length; i++) {
chrome.tabs.sendMessage(tabs[i].id, {msg: 'whatever'});
}
}
To send messages to individual content scripts will require some additional logic but is very doable (one way is to maintain some associative queue structure in the background page).
Also, note that you can use chrome.runtime.sendMessage
from inside a content script, but this will send a message to event listeners in your extension that are not inside content scripts. (So you can send a message to the background page using this method)
Upvotes: 1