Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension sendMessage error from content script to background html

I just updated my chrome extension to json version 2, and am trying to get my extension to work again. The problem is sendRequest was depreciated along the way. So I copy the code from https://developer.chrome.com/extensions/messaging.html into my script and modify it to my own variable names, and it doesn't work.

So then I go back and put in the original code and it still doesn't work. I have read multiple questions that are similar [and hopefully this won't get closed as a duplicate, because none of them were the same as my situation].

manifest.json:

{
   "background": {
        "page": "background.html"
        },
    ... ... ...
   "content_scripts": [ {
      "css": [ "style.css" ],
      "js": [ "jq.js", "script.js" ],
      "matches": [ "http://*.craigslist.org/*/*.htm*" ]
   } ],
   ... ... ...
   "permissions": [ "tabs", "http://*.craigslist.org/*/*.htm*" ],
   "manifest_version": 2,
   "update_url": "http://clients2.google.com/service/update2/crx",
   "version": "3.0"
}

background.html:

<html>
<script type='text/javascript'>
   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"});
  });
    });
</script>
</html>

script.js:

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});

Now I run a page [on craigslist], and go to the Console and this is the error:

Port error: Could not establish connection. Receiving end does not exist.
TypeError: Cannot read property 'farewell' of undefined
    at chrome-extension://dhmjefbokfkjpdbigkadjpgjeflchgea/script.js:9:23

I use Chrome Beta on Ubuntu 12.10 64-bit (Google Chrome: 27.0.1453.15 (Official Build 191758) beta)

like image 279
Matt Avatar asked Apr 08 '13 20:04

Matt


1 Answers

You are sending messages from both your background and your content script, but not trying to receive them at all. Try listening for messages in one or both of those places. Also, inline code is against the CSP so move it all to an external file.

For example:

manifest.json

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

background.js

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  sendResponse({farewell:"goodbye"});
});

script.js

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});

Also, chrome.tabs.getSelected() has been deprecated as well, so use chrome.tabs.query() instead.

like image 135
BeardFist Avatar answered Nov 15 '22 03:11

BeardFist