Google's documentation on Chrome extension development has information on passing messages between a background script and a content script. I'm trying the example code:
background.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
content_script.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
//return true;
});
They don't include a manifest file, so I created one (and three icons):
{
"background": {
"persistent": false,
"scripts": ["background.js", "content_script.js"]
},
"content_scripts": [ {
"js": ["content_script.js"],
"matches": ["<all_urls>"]
} ],
"description": "Test passing messages between a background script and a content script using Google's example code.",
"icons": {
"16": "img/icon_16x16.png",
"48": "img/icon_48x48.png",
"128": "img/icon_128x128.png"
},
"manifest_version": 2,
"name": "Test Google Chrome extension messaging",
"permissions": ["notifications"],
"version": "2017.8.25"
}
But when I load this extension, the Console reports:
Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined at chrome-extension://ibocemgcnbijkacfkpokffkfkinmenlc/background.js:3:29
I searched online for other cases of the response being undefined, and a few sources recommended adding return true;
. I tried that, but it made no difference (in the code above, it's commented out).
Can anyone see how I could get this working? Thanks!