Chrome extension sendMessage

Tom B picture Tom B · Jul 17, 2012 · Viewed 16k times · Source

The documentation here seems terrible: http://code.google.com/chrome/extensions/messaging.html

I want my content script, simply to show a pageIcon if there is a textarea on the page.

My content.js (using jquery) does this:

$('textarea').each(function() {
    chrome.extension.sendMessage({greeting: "hello"}, function(response) {
       console.log(response);
    });
});

Then my background.js has this:

chrome.extension.onMessage.addListener(

    function(request, sender, sendResponse) {
        chrome.pageAction.show(sender.tab.id);
    } 
});

Which should be incredibly simple. If there's a textarea, show the icon.

I have tried all kinds of variations from sample code and nothing works. All I ever get is:

Port error: Could not establish connection. Receiving end does not exist.

in the console.

Any ideas where I'm going wrong?

Answer

ron picture ron · Aug 17, 2012

I think you have an extra curly bracket in the background script.

chrome.extension.onMessage.addListener(

    function(request, sender, sendResponse) {
        chrome.pageAction.show(sender.tab.id);
    } 
});

should be

chrome.extension.onMessage.addListener(

    function(request, sender, sendResponse) {
        chrome.pageAction.show(sender.tab.id);
    } 
);