Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

javascript - 错误传递消息:Chrome扩展程序中的响应未定义(Error passing messages: response undefined in chrome extension)

I'm having an issue passing messages between background.js and content.js in my chrome extension.

(我在Chrome扩展程序中的background.js和content.js之间传递消息时遇到问题。)

background.js listens for a message from content.js, then returns a response.

(background.js侦听来自content.js的消息,然后返回响应。)

But that response is empty in content.js.

(但是该响应在content.js中为空。)

background.js:

(background.js:)

async function getAllTabs(callback) {
    chrome.windows.getAll({
        populate: true
    }, (windows) => {
        var tabs = [];
        windows.forEach(function (window) {
            window.tabs.forEach(function (tab) {
                tabs.push({
                    title: tab.title,
                    url: tab.url,
                    id: tab.id,
                    windowId: tab.windowId
                })
            });
        });
        if (callback) {
            console.log('callback triggered');
            callback(tabs);
        }
    });
}

chrome.runtime.onMessage.addListener(
    async function (request, sender, sendResponse) {
        if (request.action === "getAllTabs") {
            console.log("got message");
            getAllTabs(function(tabObject) {
                console.log(tabObject);
                chrome.runtime.sendMessage({action: "receiveTabs", data: tabObject});
            })
        } 
        return true;
    });

content.js:

(content.js:)

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

Both my console.logs in content.js are undefined.

(我在content.js中的两个console.logs都未定义。)

  ask by Jay Parthasarthy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...