4

I am getting this error when trying to send a message from popup to my contentscript. What I am trying to do is get the document of the current tab from my content.js and send it to the popup. How can I fix this erro?

{
  "manifest_version": 2,
  "name": "Chrome Snapshot",
  "description": "Save images and screenshots of sites to Dropbox.",
  "version": "1.0",
  "permissions": [
    "<all_urls>",
    "tabs"
  ],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "html/popup.html"
  },
  "background": {
    "scripts": [
      "vendor/dropbox.min.js",
      "vendor/jquery-2.0.2.min.js"
    ],
    "persistant": false
  },
  "content_scripts" : [{
    "all_frames": true,
    "matches" : ["*://*/*"],
    "js" : ["js/content.js"],
    "run_at": "document_end"
  }]
}

js/popup.js

chrome.runtime.sendMessage({message: 'hi'}, function(response) {
  console.log(response);
});

js/content.js

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

Edit #1 Still getting the same error Port error: Could not establish connection. Receiving end does not exist. miscellaneous_bindings:235 chromeHidden.Port.dispatchOnDisconnect

fixed mispelling 'persistent' in manifest
updated js/popup.js

chrome.tabs.query({'active': true,'currentWindow':true}, function(tab){
    console.log('from tab', tab[0]);
    chrome.tabs.sendMessage(tab[0].id, {message: 'hi'}, function(response){
      console.log(JSON.stringify(response));
    });
  });
Raptrex
  • 3,915
  • 10
  • 49
  • 61

1 Answers1

4

You'd need to use chrome.tabs.sendMessage to send messages to content scripts. From the chrome.runtime.sendMessage specification on Chrome's developer site:

Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage.

If this isn't a good option for you, you could have each content script open a port to your background page (which would probably need to be persistent) and then have your popup page send a message to your background page, which would relay the message through each of the ports to all of the content scripts to tell them to send a message back to the popup page. (Use chrome.runtime.connect.)

Also, you've misspelled "persistent" in your manifest file. I don't want you to have to dig through code for half an hour before you find out that that's been causing problems.