首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >“未检查的runtime.lastError:无法建立连接。接收端不存在”当从popup.js发送消息到content.js时

“未检查的runtime.lastError:无法建立连接。接收端不存在”当从popup.js发送消息到content.js时
EN

Stack Overflow用户
提问于 2022-09-14 14:56:25
回答 1查看 49关注 0票数 0

我看到了很多关于这个错误的问题,但是我已经尝试了所有建议的解决方案,包括禁用我的所有其他的chrome扩展,但是没有任何东西修复了这个错误。每次之后,我都会重新加载扩展,但是同样的错误不断出现。

我要提到的是,我的代码没有包含"background.js“文件,因为我没有在其中找到任何需要,但是我可能认为我不需要它是错误的,我对此非常陌生。

我的代码:

popup.js

代码语言:javascript
运行
复制
document.addEventListener("DOMContentLoaded", async () => 
{
  var activate_switch = document.querySelector("input[id=activate]");

   activate_switch.addEventListener('change', function()
   {
              if(this.checked) 
              {
                  console.log("activated");
                  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) 
                  {
                      if(tabs.length == 0)
                      { 
                          console.log("could not send mesage to current tab");
                      }
                      else
                      {
                      chrome.tabs.sendMessage(tabs[0].id, {message:"run"}, function(response)
                      {
                          console.log("Hello");
                      });
                      };  
                });
     }

          });
});

content.js

代码语言:javascript
运行
复制
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if( request.message === "run" ) {
            console.log("made it");
        }
    }
);

manifest.json

代码语言:javascript
运行
复制
{
"name": "First Chrome Extension",
"description": "Build an Extension!",
"version": "0.01",
"externally_connectable": {
    "ids": [
        "*"
    ]
},
"permissions": [
    "tabs",
    "background",
    "activeTab"
],
"action": {
    "default_title": "Scraper",
    "default_popup": "popup.html"
},
"content_scripts": [
    {
        "matches": [
            "<all_urls>"
        ],
        "js": [
            "contentScript.js"
        ],
        "run_at": "document_end"
    }
],
"manifest_version": 3

}

它会引发一个错误:

代码语言:javascript
运行
复制
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
EN

回答 1

Stack Overflow用户

发布于 2022-11-30 21:57:48

尝试删除chrome.tabs.sendMessage的回调函数。

所以,不是这样的:

代码语言:javascript
运行
复制
chrome.tabs.sendMessage(tabs[0].id, {message:"run"}, function(response)
{
    console.log("Hello");
});

就这么做吧:

代码语言:javascript
运行
复制
chrome.tabs.sendMessage(tabs[0].id, {message:"run"});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73719041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档