首页 > 解决方案 > 函数在第一次运行时返回 {},然后正常工作

问题描述

我有一个函数可以提供一些 json 数据的内容脚本。它仅在第 2 次以上运行时才能正常工作的问题。不知道如何解决它:(

let links = {};

chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {

    if (request.get == "links") {
        chrome.tabs.getAllInWindow(null, function (tabs_) {

            for (var i = 0; i < tabs_.length; i++) {
                if ((tabs_[i]['url'].match(some_var))) {
                    links[i] = [tabs_[i]['title'],
                        tabs_[i]['index']
                    ];
                }
            }
            console.log(links);              
        });

        console.log(JSON.stringify(links));
        sendResponse({reply: JSON.stringify(links)});
    }
});

我第一次运行该函数时,它返回一个空对象 {},然后工作正常。

标签: javascriptgoogle-chrome-extension

解决方案


chrome.tabs.getAllInWindow是异步的 - 所以 在get 有机会做它的事情sendResponse之前运行......把最后两行放在回调里面 - 像这样function (tabs_)

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.get == "links") {
        chrome.tabs.getAllInWindow(null, function (tabs_) {
            const links = {};
            for (var i = 0; i < tabs_.length; i++) {
                if ((tabs_[i]['url'].match(some_var))) {
                    links[i] = [tabs_[i]['title'],
                        tabs_[i]['index']
                    ];
                }
            }
            console.log(links);              
            console.log(JSON.stringify(links));
            sendResponse({reply: JSON.stringify(links)});
        });
        return true; // this signifies the response is asynchronous
    }
});

推荐阅读