Chrome 扩展程序中的接收错误:未选中的 runtime.lastError:无法建立连接。接收端不存在

vja*_*ani 5 google-chrome google-chrome-extension

我正在尝试创建一个非常简单的 Chrome 扩展程序,它允许我突出显示网页上的一个词,右键单击以打开上下文菜单,然后通过简单地将该词附加到搜索 URL,在名为 Whitaker's Words 的数据库中搜索它. 我继续收到

“未检查的 runtime.lastError:无法建立连接。接收端不存在。”

每次运行代码并尝试使用上下文菜单时都会出错。

目前,我已经采取措施禁用所有其他扩展程序,并尝试使用 Chrome Messaging Docs 上的端口文档,但我无法通过这种方式解决问题。

背景.js

    chrome.contextMenus.create({
    title: "Search Whitaker's Words",
    contexts: ["selection"]
});


chrome.contextMenus.onClicked.addListener(function() {
    chrome.runtime.sendMessage({ method: "getSelection" }, function (response) {
        sendToWW(response.data);
    });
});

function sendToWW(selectedText) {
    var serviceCall = 'http://archives.nd.edu/cgi-bin/wordz.pl?keyword=' + selectedText;
    chrome.tabs.create({ url: serviceCall });
}
Run Code Online (Sandbox Code Playgroud)

在这里,我创建了一个上下文菜单,当单击菜单项时,我向上下文脚本发送一条消息,要求突出显示的选择。然后我将其返回给 background.js 中的另一个函数,该函数将使用搜索查询创建一个新选项卡。

内容.js

chrome.runtime.onMessage.addListener(function (message) {
    if (message.method === "getSelection"){
        var word = window.getSelection().toString().trim();
        console.log(word);
        chrome.runtime.sendMessage({ data: word });
    }
    else
        chrome.runtime.sendMessage({}); // snub them.
});
Run Code Online (Sandbox Code Playgroud)

我在这里收听消息,然后从窗口中进行选择、修剪并将其发回。

清单文件

{
  "manifest_version": 2,
  "name": "Latinate",
  "version": "0.1",
  "description": "Aid in Latin translation using Whitaker's Words",
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "jquery-3.4.1.min.js",
        "content.js"
      ]
    }
  ],
  "background": {
    "scripts": [
      "background.js"
    ]
  },
  "permissions": [
    "contextMenus",
    "tabs"
  ],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}
Run Code Online (Sandbox Code Playgroud)

任何和所有的帮助将不胜感激!我已经尝试了几乎所有我能找到的似乎适用的方法。

wOx*_*xOm 4

错误消息表明另一端没有消息侦听器。事实上没有,因为消息侦听器是使用 chrome.runtime.onMessage.addListener 注册的函数 - 在您的扩展中,只有内容脚本具有这样的侦听器。

不要发回新消息,而是使用 sendResponse 函数发送响应,该函数作为参数传递给onMessage侦听器
(另请参阅消息传递教程)。

另一个问题是,要将消息发送到选项卡,您需要使用不同的方法:chrome.tabs.sendMessage,并将选项卡 id 作为第一个参数。

后台脚本:

chrome.contextMenus.onClicked.addListener((info, tab) => {
  chrome.tabs.sendMessage(tab.id, {method: 'getSelection'}, response => {
    sendToWW(response.data);
  });
});
Run Code Online (Sandbox Code Playgroud)

内容脚本:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.method === 'getSelection') {
    var word = window.getSelection().toString().trim();
    console.log(word);
    sendResponse({ data: word });
  } else {
    sendResponse({});
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 此外,当您编辑内容/背景脚本时,您需要在“chrome://extensions”页面上重新加载扩展程序,并重新加载网络选项卡。 (5认同)