繁体   English   中英

函数在第一次运行时返回{},然后正常工作

[英]Function returns {} on the first run and then works correctly

我有一个功能,旨在为内容脚本提供一些json数据。 该问题仅在第二次运行时才能正常运行。 不知道如何解决它:(

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)});
    }
});

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

chrome.tabs.getAllInWindow是异步的-因此sendResponsefunction (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
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM