【问题标题】:Callback function won't fire after sendResponse()回调函数不会在 sendResponse() 之后触发
【发布时间】:2022-11-29 06:48:48
【问题描述】:

我想在我的后台服务工作者和我的内容脚本之间进行通信,但即使我添加了回调,它也不会触发

内容.js

setInterval(function () {
        chrome.runtime.sendMessage({
            message: "is-playing", callback: function (counter) {
                console.log("Callback")
                console.log(counter);
            }
        })
}, 2000);`

背景.js

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        sendResponse({ counter: request.counter + 1 });
        console.log("send response")
        console.log(chrome.runtime.lastError)
    });

我试图通过检查错误chrome.runtime.lastError但即使这样也行不通

【问题讨论】:

    标签: javascript google-chrome-extension


    【解决方案1】:
    chrome.runtime.sendMessage(
        {state: "is-playing"}, function(counter) {
            console.log("Callback")
            console.log(counter);
        }
    )
    

    {state: "is-playing"} 是“消息” function(counter) {...} 是“回调”。

    由于您每 2 秒发送一条消息,因此我建议您使用long-live connection

    【讨论】:

      猜你喜欢
      • 2011-11-23
      • 2015-03-29
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 2010-10-09
      • 1970-01-01
      • 2015-10-27
      相关资源
      最近更新 更多