1

I am trying to implement message passing from background script to content script

manifest.json

"background": {
        "scripts": ["background.js"],
        "persistent": false
    },

    "content_scripts" : [
    {
        "matches" : [ "http://*/*" ],
        "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")
      sendResponse({farewell: "goodbye"});
  });

I am getting the error Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined

I have gone extensively through StackOverflow and also implemented this solution but to no avail.

Community
  • 1
  • 1
Piyush
  • 606
  • 4
  • 16
  • 38
  • 1
    check json file on http://jsonlint.com/ –  Dec 13 '15 at 20:35
  • The posted code doesn't have any errors. Use the debugger to set breakpoints in the background script and content script and see what actually happens. – wOxxOm Dec 14 '15 at 00:39
  • Getting the same error. Json seems valid. However, it suddenly ran for a while this morning and then on reloading it, I seem to be getting the same error again. I honestly don't know what is going on and how it works a few times while I get the farewell error on other instances. I think it may have something to do with navigating to specific tabs – Piyush Dec 14 '15 at 08:05
  • Whatever _sets_ the alarm you're listening to? – Xan Dec 14 '15 at 11:35
  • Also, note that you only inject on `http:` pages. This would happen (because there is no listener) if you're not currently focused on a `http:` page. – Xan Dec 14 '15 at 11:46
  • @Xan I am setting the alarm using a chrome.alarms.create command. I noticed something interesting. Some pages are throwing a popup while some aren't. All https (note the s) aren't while some http are while a few aren't. For ex: zenhabits.com is throwing a popup and stackoverflow isn't. Also, I can only see the console command goodbye printed. I don't see the sender.tab console command in content script. Is this normal behaviour? – Piyush Dec 14 '15 at 19:29
  • Seems like I am able to get a popup on the page if I refresh a particular tab. 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, the console commands in the content script aren't getting printed. How do I correct this? – Piyush Dec 14 '15 at 19:43

0 Answers0