I\'ve already read the documentation from Google on \'message passing\' a few times and have probably looked at over 10 other questions with the same problem and already tri
Careful reading of this answer may help you. Every point there applies to your problem.
Your problem is in when your main script is executing, and when your content scripts are. You need to ensure there is a content script listening before you send a message to it, in worst case injecting it programmatically.
And to get it working in a popup, follow KAdot's answer.
Here is the solution, using background script:
{
"manifest_version" : 2,
"name" : "Message Test",
"version" : "1.0",
"background":{
"scripts":["popup.js"]
},
"content_scripts": [
{
"matches" : ["<all_urls>"],
"js": ["message-test.js"]
}
]
}
var port = chrome.runtime.connect();
port.onMessage.addListener(function(message, sender, sendResponse) {
if (message.greeting == "Can you hear me?"){
alert("Test");
}
else{
sendResponse({});
}
});
chrome.runtime.onConnect.addListener( function ( port ) {
port.postMessage({
greeting: "Can you hear me?"
});
});
Some explanaition: first we are connecting to our background script from content script and then background script sends message to content script.
I've improved answer according to @Xan remark. But the idea is the same, first of all you should let know your background script of the existence of content script.
There are several issues in your code.
Chrome doesn't allow inline scripts in extensions. You must divide your popup.html to script + HTML:
// popup.html
<html>
<body>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
// popup.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var tab = tabs[0]; // do not forget to declare "tab" variable
chrome.tabs.sendMessage(tab.id, {
greeting: "Can you hear me?"
}, function(response){});
});