Reputation: 761
i'm trying sending data from website javascript to my chrome extension. I read about sending msgs from website and i couldn't make it work.
in my website:
$("#button-id").click(function(){
chrome.runtime.sendMessage("msg", {arg: "1"},
function(response){alert("got response: " + response);});
});
and in background.js (in the chrome extension)
chrome.runtime.onMessageExternal.addListener(
function() {
alert("in background");
return "1";
});
I also added to the manifest:
"externally_connectable": {
"matches": ["*://localhost/project/public/*","http://localhost/project/public/*","*://*/*/*"]
},
and all I'm getting when I'm clicking that button is alert that says "got response undefined".
something that i tried that maybe will help to figure it out: when I'm on my website, opening chrome developer console, typing "chrome.runtime.sendMessage("jjj");" I'm getting 'undefined'.
thanks in advance!!!
Upvotes: 0
Views: 1087
Reputation: 77591
To send a response, you need to pass it to sendResponse
parameter of the listener, which is the third parameter:
chrome.runtime.onMessageExternal.addListener(
function(message, sender, sendResponse) {
alert("in background");
sendResponse("1");
}
);
One thing to note: if sendResponse
is going to be called asynchronously, you have to return true;
Also, when sending a message from a webpage, you have to supply the extension's id as the first parameter. In your example code it's "msg"
: it must be an extension id.
Upvotes: 3