首页 > 解决方案 > Chrome 扩展:未选中 runtime.lastError:无法建立连接。接收端不存在

问题描述

最近,据报道我的应用程序的上下文菜单消失了。如果您删除该应用程序并重新安装它,它就可以工作。但消失又发生了。

我发现了一个错误。我不确定该错误是否会导致上下文菜单消失。但我想解决这个问题,因为我发现的就是这个。

此应用程序显示您在页面中选择的文本。当您在普通页面中选择文本并单击浏览器操作按钮时,它可以正常工作。但是如果你在 Google Docs 上尝试,你会得到错误“Unchecked runtime.lastError: 无法建立连接。接收端不存在”。

恐怕我不知道该怎么办。我可能有两个问题。如果你能给我一些建议,那将是很大的帮助。

[清单.js]

{
    "manifest_version": 2,
    "name": "Test Chrome Extension",
    "short_name": "Test",
    "version": "1.0",
    "description": "This is a test.",
    "icons": {
        "128": "128.png"
    },
    "content_scripts": [{
        "matches": ["<all_urls>"],
        "js": ["googleDocsUtil.js", "content_scripts.js"]
    }],
    "background": {
        "scripts": ["background.js"],
        "persistent": true
    },
    "browser_action": {
        "default_icon": {
            "48": "48.png"
        },
        "default_title": "Test Chrome Extension"
    },
    "permissions": [
        "contextMenus",
        "tabs",
        "background",
        "http://*/*",
        "https://*/*"
    ]
}

[背景.js]

chrome.contextMenus.create({
    type: 'normal',
    id: 'testchromeextension',
    title: 'Test Chrome Extension',
    contexts:['selection']
});

chrome.contextMenus.onClicked.addListener(function(info,tab){
    if( info.menuItemId == 'testchromeextension' ){
        var selectedText = info.selectionText.replace(/ /g, "\n");
        doSomething(selectedText);
    }
});

chrome.browserAction.onClicked.addListener( function(tab) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {method: "getSelection"}, function(response) {
            doSomething(response.data);
        });
    });
});

function doSomething(selectedText) {
    console.log(selectedText);
}

[content_scripts.js]

chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
    if (request.method == "getSelection") {
        var post_val = window.getSelection().toString();
        if ( !post_val ) {
            var googleDocument = googleDocsUtil.getGoogleDocument();
            post_val = googleDocument.selectedText;
        }
        sendResponse({data: post_val});
    }
});

标签: google-chrome-extension

解决方案


我相信当您更新扩展的本地版本然后尝试将扩展与旧/未更新的源代码一起使用时会导致此错误。

修复:在 重新加载本地扩展后chrome://extensions/,请确保刷新您在 上使用扩展的页面。您应该不再看到该错误。


推荐阅读