javascript - 浏览器.tabs.sendMessage() : Error: Receiving end does not exist

标签 javascript firefox-addon-webextensions

我试图运行在 tabs.sendMessage() MDN page 上给出的示例代码.所以我的代码是:

list .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"});
});

我使用 web-ext run 运行它,在单击浏览器操作按钮后,在控制台中我收到此消息:错误:错误:无法建立连接。接收端不存在

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

这,在浏览器控制台中,第一条消息出现在我安装它之前。我的意思是它在安装之前就在那里,所以它会静默安装。单击按钮后,我收到了最后两条消息,第一条消息从这一行 console.log(tab.id) 给出了 tab.id 然后是错误:

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

最佳答案

当没有 runtime.onMessage 时,您看到的错误结果在对 tabs.sendMessage() 的调用中指定的选项卡中,由内容脚本为您的扩展程序定义的监听器.这可能是因为没有内容脚本,或者因为已注入(inject)的内容脚本没有为 runtime.onMessage 添加监听器。

您应该记住,您不能将内容脚本注入(inject)到具有 about:newtababout:debugging 等 URL 的页面中。此外,Firefox 会不允许您将脚本注入(inject) addons.mozilla.org 上的页面。

您的问题很复杂,因为您的 Match Pattern可能不是你想要的。您可能希望您的匹配是:

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

注意匹配模式末尾的 *。您当前使用的模式 "*://*/" 将仅匹配使用 httphttps 加载的任何域的首页 方案。例如,它不会匹配 https://www.google.com/?gws_rd=ssl,但会匹配 http://www.example.com/

鉴于您的代码是在用户单击浏览器或页面操作按钮时直接执行的,您需要以某种合理的方式处理此错误,向用户提供他们所请求的操作无法完成的反馈,因为用户单击about:newtab 等页面上的按钮,导致此错误。你如何处理这个错误,将取决于你的代码在做什么。与其设置用户单击他们希望工作的已启用按钮的情况,更好的选择是在您无法执行代码的页面上禁用您的操作按钮(对于浏览器操作,使用 browserAction.disable() ) .

关于javascript - 浏览器.tabs.sendMessage() : Error: Receiving end does not exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42147966/

相关文章:

javascript - axios 超时重试

javascript - 如何在 Firefox WebExtension 中查看后台脚本的 console.log 输出?

firefox-addon-webextensions - Firefox WebExtension API "browser is not defined"

javascript - 在 WebExtensions(JavaScript、Firefox)中读取 LZ4 压缩文本文件 (mozlz4)

javascript - 通知在 FF Web 扩展中不起作用

javascript - React 中使用鼠标滚轮缩放图像

javascript - Jqgrid treeGridModel 中的组标题

javascript - 使用 vanilla js 和 css 的动画移动动画

javascript - 非阻塞函数返回后的 Node.js 回调处理

javascript - 如果选项页面有 onMessage 监听器,则内容脚本 sendMessage 会收到 null