首页 > 解决方案 > 即使我返回 true,Chrome 事件侦听器 SendResponse 也不会发送

问题描述

遇到与Chrome 扩展消息传递相同的问题:未发送响应。但是,当我实施建议的解决方案时,它并不能解决我的问题。我得到了完全相同的错误,并且在返回响应之前还调用了一个异步方法。这里出了什么问题???

背景.js

chrome.runtime.onMessage.addListener(
    async function (request, sender, sendResponse) {
        if (request.action === "getAllTabs") {
            // if I uncomment this line, content.js receives this response
            // sendResponse({data: "hey"})
            chrome.tabs.query({}, function(tabs){
                // but not this one??
                sendResponse({data: tabs});
            })
            console.log('returning true');
            return true;

我的 content.js:

    chrome.runtime.sendMessage({action: "getAllTabs"}, function(response) {
      console.log(response);
    });

标签: javascriptgoogle-chrome-extension

解决方案


推荐阅读