I am trying to implement message passing from background script to content script
manifest.json
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts" : [
{
"matches" : [ "<all_urls>" ],
"js": ["hello.js"],
"css": [ "hello.css" ]
}
background.js
function showpopup()
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
}
chrome.alarms.onAlarm.addListener(showpopup);
content script js aka hello.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") {
alert("Hello World");
sendResponse({farewell: "goodbye"});
}
});
I am getting the error Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined
I am setting an alarm in the background page using a chrome.alarms.create command. I noticed something interesting. Some pages are throwing a popup while others aren't.
Seems like I am able to get a popup on the page if I refresh a particular tab.(I have around 10 open) On opening or refreshing a new tab, I am getting a popup whereas an old tab doesn't show a popup. Does anyone know how to correct this?
Also is there a way to match chrome:// and newtab pages as well in the manifest? I tried including chrome:// but that didn't work as intended.