小编vja*_*ani的帖子

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

我正在尝试创建一个非常简单的 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)

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

清单文件 …

google-chrome google-chrome-extension

5
推荐指数
1
解决办法
3077
查看次数