Tom B
Tom B

Reputation: 2923

Chrome extension sendMessage

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?

Upvotes: 7

Views: 20520

Answers (1)

ron
ron

Reputation: 1097

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

Upvotes: 7

Related Questions