0

I've been trying to get message passing for a chrome extension to work but console.log(response) gives me undefined. I've looked at the docs for message passing and on stackoverflow, but in my case it won't work. I am at a loss as to why.

myscript.js:

chrome.extension.sendRequest({greeting: "hello"}, function(response) {
    console.log(response);
    return true;
});

background.js:

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

manifest.json

{
  "manifest_version": 2,

  "name": "nameasf",
  "description": "asfasaf",
  "version": "1.0",

  "permissions": [
    "tabs",
    "http://somedomain.com/"
  ],

    "content_scripts": [
    {
      "matches": ["http://somedomain.com/*"],
      "css": ["mystyles.css"],
      "js": ["jquery.js", "myscript.js"],
      "all_frames": true
    }
  ],

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

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}
  • possible duplicate of [Chrome Extension: Port error: Could not establish connection. Receiving end does not exist.](http://stackoverflow.com/questions/11811554/chrome-extension-port-error-could-not-establish-connection-receiving-end-does) – Rob W Dec 05 '13 at 20:38

1 Answers1

0

You are using the obsolete chrome.extension.sendRequest.
Use chrome.runtime.sendMessage instead.

(Note: You are already using the new chrome.runtime.onMessage so you don't have to change anything on the listener side.)


A couple of sidenotes:

  • For the code presented here you don't need any permission (especially not the powerful tabs permission).
  • And it is a good idea to use non-persistent background pages (a.k.a. event-pages) whenever possible as they are considerably more resource-friendly.
Rob W
  • 341,306
  • 83
  • 791
  • 678
gkalpak
  • 47,844
  • 8
  • 105
  • 118
  • Ah, yes, excessive cutting and pasting from various sources screwed it up for me. :) Anyway, the original problem was that I reloaded the extension with an "extension reloader" isntead of reloading it from chrome://extensions. It needed permission reloading as well it seems. – Arvin Johansson Arbab Dec 05 '13 at 21:01