Reputation: 783
manifest
{
"manifest_version": 2,
"name": "sth",
"description": "sth",
"version": "0.1",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon": "icon.png"
},
"externally_connectable": {
"ids": [
"mmaocogodokhpkellandkpdknpnihple"
],
"matches": [
"https://*.google.de/*"
],
"accepts_tls_channel_id": false
},
"permissions": [
"activeTab"
]
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "content.js"});
});
chrome.runtime.onMessageExternal.addListener( function(request, sender, sendResponse) {
console.log(request);
return true;
});
content.js
console.log("content");
var msg = { text: "test" };
chrome.runtime.sendMessage("mmaocogodokhpkellandkpdknpnihple", msg, function() {
console.log("content callback");
});
When on https://www.googel.de I click on the icon and see "content" and "content callback"in the console, but the request isn't logged in the console of the background-script. I probably miss something here... ?
(Chrome 44 on Linux)
Upvotes: 1
Views: 1335
Reputation: 77523
Messages inside your own extension are not external. You need the regular, boring messages with onMessage
and without specifying the ID.
// background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "content.js"});
});
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
console.log(request);
return true; // Why? This keeps the communication channel open waiting,
// and then you won't see "content callback"
});
.
// content.js
console.log("content");
var msg = { text: "test" };
chrome.runtime.sendMessage(msg, function() {
console.log("content callback");
});
Indeed, maybe returning true
got you confused? It's needed when you plan to call sendResponse
asynchronously, and so the callback of sendMessage
won't fire until you do.
Upvotes: 1