4

I trying to run example code given on the tabs.sendMessage() MDN page. So my code is:

manifest.json:

{
    "manifest_version": 2,
    "name": "test1",
    "version": "1.0",
    "description": "test",
    "icons": {
        "48": "icons/Ruler48.png"
    },
    "permissions": [
        "notifications",
        "tabs",
        "activeTab"
    ],
    "browser_action": {
        "default_icon": "icons/Ruler48.png",
        "default_title": "test"
    },
    "content_scripts": [{
        "matches": ["*://*/"],
        "js": ["content-script.js"]
    }],
    "background": {
        "scripts": ["bgS.js"]
    }
}

bgS.js:

function onError(error) {
  console.error(`Error: ${error}`);
}

function sendMessageToTabs(tabs) {
  for (let tab of tabs) {
    console.log(tab.id);
    browser.tabs.sendMessage(
      tab.id,
      {greeting: "Hi from background script"}
    ).then(response => {
      console.log("Message from the content script:");
      console.log(response.response);
    }).catch(onError);
  }
}

browser.browserAction.onClicked.addListener(() => {
  browser.tabs.query({
    currentWindow: true,
    active: true
  }).then(sendMessageToTabs).catch(onError);
});

content-script.js:

browser.runtime.onMessage.addListener(request => {
  console.log("Message from the background script:");
  console.log(request.greeting);
  return Promise.resolve({response: "Hi from content script"});
});

I run it with web-ext run, after clicking on browser action button, in the console I get this message: Error: Error: Could not establish connection. Receiving end does not exist.

The output from web-ext run --verbose

 web-ext run --verbose
[program.js][debug] Getting the version from package.json
[program.js][info] Version: 1.8.0
[program.js][debug] Getting the version from package.json
[cmd/run.js][info] Running web extension from C:\test
[util/manifest.js][debug] Validating manifest at C:\test\manifest.json
[cmd/run.js][debug] Creating new Firefox profile
[cmd/run.js][debug] Deferring extension installation until after connecting to the remote debugger    
[firefox/index.js][debug] Checking if remote Firefox port 6005 is available
[firefox/remote.js][debug] Connecting to Firefox on port 6005
[firefox/index.js][debug] Executing Firefox binary: C:\Program Files\Mozilla Firefox\firefox.exe    
[firefox/index.js][info] Use --verbose or open Tools > Web Developer > Browser Console to see logging
[cmd/run.js][debug] Connecting to the remote Firefox debugger
[firefox/remote.js][debug] Connecting to Firefox on port 6005
[cmd/run.js][debug] Retrying Firefox (0); connection error: Error: connect ECONNREFUSED 127.0.0.1:6005
[firefox/remote.js][debug] Connecting to Firefox on port 6005
[cmd/run.js][debug] Retrying Firefox (1); connection error: Error: connect ECONNREFUSED 127.0.0.1:6005
[firefox/remote.js][debug] Connecting to Firefox on port 6005
[cmd/run.js][debug] Retrying Firefox (2); connection error: Error: connect ECONNREFUSED 127.0.0.1:6005
[firefox/remote.js][debug] Connecting to Firefox on port 6005
[firefox/index.js][debug] Firefox stdout: Started debugger server on 6005
[cmd/run.js][debug] Retrying Firefox (3); connection error: Error: connect ECONNREFUSED 127.0.0.1:6005
[firefox/remote.js][debug] Connecting to Firefox on port 6005
[firefox/remote.js][debug] Connected to the remote Firefox debugger
[firefox/index.js][debug] Firefox stderr: JavaScript strict warning: resource://gre/modules/commonjs/toolkit/loader.js -> resource://devtools/shared/security/socket.js, line 778: ReferenceError: reference to undefined property this._handshakeTimeout
[firefox/index.js][debug] Firefox stderr: JavaScript strict warning: chrome://browser/content/browser.js, line 6573: SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
[firefox/remote.js][debug] installTemporaryAddon: {"addon":{"id":"d71da5f6ee8174302deb5edfa887679913cd71ed@temporary-addon","actor":false},"from":"server1.conn0.addonsActor3"}
[firefox/remote.js][info] Installed C:\test as a temporary add-on
[cmd/run.js][info] The extension will reload if any source file changes
[util/file-filter.js][debug] Resolved path **/*.xpi with sourceDir C:\test to C:\test\**\*.xpi
[util/file-filter.js][debug] Resolved path **/*.zip with sourceDir C:\test to C:\test\**\*.zip
[util/file-filter.js][debug] Resolved path **/.* with sourceDir C:\test to C:\test\**\.*
[util/file-filter.js][debug] Resolved path **/.*/**/* with sourceDir C:\test to C:\test\**\.*\**\*
[util/file-filter.js][debug] Resolved path **/node_modules with sourceDir C:\test to C:\test\**\node_modules
[util/file-filter.js][debug] Resolved path **/node_modules/**/* with sourceDir C:\test to C:\test\**\node_modules\**\*
[util/file-filter.js][debug] Resolved path C:\test\web-ext-artifacts with sourceDir C:\test to C:\test\web-ext-artifacts
[util/file-filter.js][debug] Resolved path C:\test\web-ext-artifacts\**\* with sourceDir C:\test to C:\test\web-ext-artifacts\**\*
[watcher.js][debug] Watching for file changes in C:\test
[firefox/index.js][debug] Firefox stderr: JavaScript strict warning: chrome://browser/content/tabbrowser.xml, line 640: ReferenceError: reference to undefined property this.mBrowser.initialPageLoadedFromURLBar
[firefox/index.js][debug] Firefox stdout: 1486682957594 addons.webextension.d71da5f6ee8174302deb5edfa887679913cd71ed@temporary-addon    WARN    Please specify whether you want browser_style or not in your browser_action options.
[firefox/index.js][debug] Firefox stderr: JavaScript strict warning: chrome://global/content/bindings/browser.xml, line 385: ReferenceError: reference to undefined property tabBrowser.localName
[firefox/index.js][debug] Firefox stderr: JavaScript strict warning: resource://gre/modules/commonjs/toolkit/loader.js -> resource://devtools/shared/node-properties/node-properties.js, line 134: ReferenceError: reference to undefined property control.resume
[firefox/index.js][debug] Firefox stderr: JavaScript strict warning: resource://gre/modules/commonjs/toolkit/loader.js -> resource://devtools/shared/node-properties/node-properties.js, line 124: ReferenceError: reference to undefined property options._comments[c]
[firefox/index.js][debug] Firefox stderr: JavaScript strict warning: resource://gre/modules/commonjs/toolkit/loader.js -> resource://devtools/shared/node-properties/node-properties.js, line 130: ReferenceError: reference to undefined property options._separators[c]
[firefox/index.js][debug] Firefox stderr: JavaScript strict warning: resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/commonjs/sdk/system/unload.js, line 31: ReferenceError: reference to undefined property observers[i].value
[firefox/index.js][debug] Firefox stderr: JavaScript strict warning: resource://gre/modules/ProfileAge.jsm, line 202: ReferenceError: reference to undefined property times.reset
[firefox/index.js][debug] Firefox stderr: JavaScript strict warning: resource://gre/modules/LoginStore.jsm, line 275: ReferenceError: reference to undefined property this.data.version
[firefox/index.js][debug] Firefox stderr: JavaScript strict warning: chrome://global/content/bindings/browser.xml, line 385: ReferenceError: reference to undefined property tabBrowser.localName

This, what in browser console, the first message appear before I install it. I mean it was there before installation, so it installs silently. After clicking on button I got last two messages, the first one gives tab.id from this line console.log(tab.id) and then error:

1486683758937   addons.webextension.16f1634b55daa52a653f3a2ba33358a691bb015a@temporary-addon    WARN    Please specify whether you want browser_style or not in your browser_action options.
10  bgS.js:8:3
Error: Error: Could not establish connection. Receiving end does not exist.  bgS.js:3:3
Makyen
  • 31,849
  • 12
  • 86
  • 121
  • What, *exactly*, was shown in the [Browser Console](https://developer.mozilla.org/en-US/docs/Tools/Browser_Console) (Ctrl-Shift-J, or Cmd-Shift-J on OSX) when you tried to install and use the extension? – Makyen Feb 09 '17 at 23:18
  • When you click on your browser action button, does the active tab contain a page with a URL that begins with `http://` or `https://`? Are you doing then when viewing a tab with a URL like `about:addons`, `about:debugging`, etc.? Are you trying to use this on a page on [AMO](https://addons.mozilla.org/)? – Makyen Feb 09 '17 at 23:22
  • Don't know if that what you ask for but when i run it with web-ext run --verbose i get this. I updated question. – someNameJustToAnswer Feb 09 '17 at 23:31
  • I tried it with https://www.google.com still same effect Error: Error: Could not establish connection. Receiving end does not exist. bgS.js:3:3 – someNameJustToAnswer Feb 09 '17 at 23:37
  • Updated with Browser console output. – someNameJustToAnswer Feb 09 '17 at 23:50
  • Very interesting. Ok, here is the thing, after clicking on one of a link on page that was loaded in tab and after new page was loaded after click on addon button it seems to work as it shows 1 bgS.js:8:3 Message from the content script: bgS.js:13:7 Hi from content script bgS.js:14:7. – someNameJustToAnswer Feb 10 '17 at 00:16
  • Makyen, how to accept your comment as answer? Thanks! – someNameJustToAnswer Feb 10 '17 at 00:18
  • I'll write up an answer. Just to double check: You were experiencing this issue when you pressed your browser action button on the tab that was initially shown when you ran `web-ext run`, but once you navigated to a normal `http`/`https` page it functioned correctly. Is that correct? – Makyen Feb 10 '17 at 00:49
  • Actually the situation more complicated. i will try explain it in details. i need addon that will fetch some data from web page. So, for not navigating it every time, i just saved this page on local drive and tried to run some parsing on it, (actually i not get to this stage i stuck on reacting on button click) but soon i find out that it does not work. So as you suggested i tried to load some http https page and (when addon was installed) i navigate to google then clicked on addon button, nothing, then, i don’t know why – someNameJustToAnswer Feb 10 '17 at 01:22
  • i just clicked on some link and after it loaded, content script seems attach to it and worked. But if i just type some url and navigate to it, it still not working. So now i looking on browser.tabs.executeScript and will try to push it that way. – someNameJustToAnswer Feb 10 '17 at 01:23
  • BTW: If your user interaction *begins* with clicking a browser UI button, then the content script should be injected with [`chrome.tabs.executeScript()`](https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/executeScript) instead of a *manifest.json* `content_script` entry. That way, your content script does not burden the browser by being injected into every page just to wait to be used. Using `chrome.tabs.executeScript()`, the script can begin functioning when it is injected with [the data, if any needed, that has been passed to it](http://stackoverflow.com/a/40815514/3773011). – Makyen Feb 10 '17 at 03:15

1 Answers1

9

The error you are seeing results when there is no runtime.onMessage listener defined by a content script for your extension in the tab which was specified in the call to tabs.sendMessage(). This can be because there is no content script or because the content script(s) which have been injected have not added a listener for runtime.onMessage.

You should keep in mind that you can not inject content scripts into pages that have URLs like about:newtab, about:debugging, etc. In addition, Firefox does not permit you to inject scripts into pages on addons.mozilla.org.

Your issue was compounded because your Match Pattern is probably not what you intended it to be. You probably intended your matches to be:

"matches": ["*://*/*"],

Note the trailing * at the end of the match pattern. The pattern you are currently using "*://*/" will only match the top page on any domain which is loaded using either the http or the https scheme. For instance, it will not match https://www.google.com/?gws_rd=ssl, but will match http://www.example.com/.

Given that your code is executing directly upon a user's click of a browser or page action button, you need to handle this error in some reasonable manner that provides feedback to the user that what they have requested can not be done, because the user will click the button on pages like about:newtab, which will result in this error. How you handle this error, will depend on what your code is doing. Rather than setting up a situation where the user is clicking on an enabled button which they expect to work, the better alternative is to disable your action button (for browser actions, using browserAction.disable()) on pages for which you can not execute your code.

Makyen
  • 31,849
  • 12
  • 86
  • 121
  • I had exactly this issue ("Receiving end does not exist") when the background (script) sends the message before the content_script(s) had a chance to register the callback. Adding some console.log messages and a delay (see [How to delay execution in between the following in my javascript](https://stackoverflow.com/questions/5990725/how-to-delay-execution-in-between-the-following-in-my-javascript#5990760)) will do to reproduce/hot fix this issue. Do not use the delay method for a reliable production script. – coseos May 29 '20 at 08:50