Chrome扩展程序错误“未经检查的runtime.lastError:消息端口在收到响应之前已关闭”]]

问题描述 投票:0回答:1

我试图从popup.js中简单地在background.js中调用一个函数。但是,我得到了“未经检查的runtime.lastError:在收到响应之前,消息端口已关闭”。错误。

我最初的“握手”消息运行正常,没有错误,但是我的“ AnotherMessage”得到了以上错误。

我正在尝试遵循发现的here onMessage和sendMessage文档,但我可能做错了。

popup.js

//works perfectly fine
chrome.runtime.sendMessage({msg:"Handshake"}, response => {
    if(response.error){
        console.log(response);
    }
});

//Gives error message
chrome.runtime.sendMessage({msg:"AnotherMessage"}, response => {
    if(response.error){
        console.log(response);
    }
});

我想要两个'sendMessage'的原因是我想根据特定的逻辑在background.js中执行特定的功能。

background.js

chrome.runtime.onMessage.addListener((request,sender,sendResponse){
if(request.msg === "Handshake"){
    //Do something
} else if (request.msg === "AnotherMessage") {
    //Do something else
   }
});

更新:要添加一些上下文,我的扩展名基本上有两种形式。我想将表单提交的数据发送到我的数据库,因此'form-1

'提交将执行'function-1',而'form-2'提交应执行' function-2'在background.js中。我正在尝试通过sendMessage和onMessage实现不同的功能执行。

我试图从popup.js中简单地在background.js中调用一个函数。但是,我得到了“未经检查的runtime.lastError:在收到响应之前,消息端口已关闭”。错误。我最初的'...

javascript google-chrome-extension sendmessage message-passing chrome-runtime
1个回答
-1
投票

在后台脚本中,如果调用sendResponse异步,则必须从回调函数返回true]]

 chrome.runtime.onMessage.addListener((request,sender,sendResponse){
    if (request.msg === "Handshake"){
        //Do something
    } else if (request.msg === "AnotherMessage") {
        //Do something else
   }
   return true;   
});
© www.soinside.com 2019 - 2024. All rights reserved.