7

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?

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
Tom B
  • 2,735
  • 2
  • 24
  • 30
  • 2
    The documentation for Chrome extensions is generally excellent. You did not properly read the documentation: Event listeners to [`chrome.extension.onmessage`](http://code.google.com/chrome/extensions/extension.html#event-onMessage) receive only one parameter: The object containing `request`, `sender`, `sendResponse`. (since Chrome 20, [`onRequest` and `sendRequest` have been replaced with `onMessage` and `sendMessage`](http://stackoverflow.com/a/11412113)). This is probably not the cause of the error though. Are you sure that the `onMessage` event listener is attached (ie no error occurred)? – Rob W Jul 17 '12 at 21:35
  • Change onMessage to onRequest and try again, if error persists then you have to look at console log of background script (in Extensions -> Inspect Views: *** there should be your script, jusc lick and go to console, look at error message) – Aleksandar Toplek Jul 18 '12 at 11:30

1 Answers1

7

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);
    } 
);
ron
  • 1,048
  • 7
  • 16
  • I'm calling sendResponse(from extension) back to send some content but not getting called.Please help. – pavan Sep 24 '14 at 14:33