Chrome.runtime.sendMessage in content script does not send message

I have the following files ( gist for easy access):

manifest.json

{ "name": "testmessage", "version": "0.1", "manifest_version": 2, "externally_connectable": { "matches": ["*://www.google.com/*"] }, "background": { "scripts": ["background.js"], "persistent": true }, "content_scripts": [ { "matches": ["*://www.google.com/*"], "js": ["content.js"] } ] } 

content.js

 chrome.runtime.sendMessage( "eldkfaboijfanbdjdkohlfpoffdiehnb", // PUT YOUR EXTENSION ID HERE "foo", function (response) { console.log(response); } ); console.log("this is content.js reporting for duty"); 

background.js

 chrome.runtime.onMessageExternal.addListener( function(request, sender, sendResponse) { console.log("background.js got a message") console.log(request); console.log(sender); sendResponse("bar"); } ); console.log("this is background.js reporting for duty"); 

I can see messages "... messages for official duties" in the corresponding consoles. But background.js does not receive the message when http://www.google.com loads. Line 5 in content.js prints undefined in the console for google.com.

When I run chrome.runtime.sendMessage("eldkfaboijfanbdjdkohlfpoffdiehnb", "foo"); in google.com console, it is displayed in background.js console.

What am I doing wrong?

+6
source share
1 answer

What you do wrong makes it too complicated. Twice.

First, you do not need to declare that you can connect from the outside, as you are sending a message from the content of the script, not the web page itself.

Secondly, this is not an external message. External messages are designed to connect different extensions, not messages within the same extension.

Your code should look like this:

content.js

 chrome.runtime.sendMessage( "foo", function (response) { console.log(response); } ); 

background.js

 chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { console.log("background.js got a message") console.log(request); console.log(sender); sendResponse("bar"); } ); 
+12
source

All Articles