Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Making chrome extension and chrome.runtime.onMessage isn't receiving the message


Here is the code in my event page:

chrome.runtime.onInstalled.addListener(function (){
    chrome.contextMenus.create
        ({
            "title": "Test",
            "contexts": ["all"],
            "id": "menu"
        });
    chrome.contextMenus.create
        ({
            "title": "Dummy",
            "contexts": ["all"],
            "id": "dummy",
            "parentId": "menu"
        });
});

chrome.contextMenus.onClicked.addListener(onClickHandler);

function onClickHandler (info, tab) {
    if(info.menuItemId == "dummy"){
        chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {
            console.log(response.farewell);
        });  
    }
}

And here is the code in my content script straight from the chrome message passing documentation:

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"});
  });

The onClickHandler in the event page is being triggered, but it seems like the sendMessage method isn't working. The onMessage listener isn't receiving any information, so it doesn't log anything to the console or even send a response. This causes the original sendMessage callback to throw an exception because response.farewell isn't even defined. Does anybody know why the code doesn't seem to work.

The error:

Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined

Solution

  • Turns out there wasn't a problem with the code in the content script or the event page.

    This thread: Chrome extension Content Script not loaded until page is refreshed

    Helped me realize that the content script wasn't running because of the site I was testing it on, and because it wasn't running it obviously couldn't listen for any events.