Chrome API

时间:2017-05-27 15:24:49

标签: javascript google-chrome google-chrome-extension

以前曾问过很多类似的问题,但我相信这是不同的。请仔细阅读以了解情况。

我知道chrome API是异步的。

所以,我正在做的是为某些网站提取cookie:

var myUrl = ["mywebsite.com","mywebsite2.com","mywebsite3.com","mywebsite4.com"]; 
    var outLine = {};
    var aE;
    for (var i = 0; i < myUrl.length ; i++) {   
        outLine[myUrl[i]] = {};
        chrome.cookies.getAll({domain: myUrl[i]}, function(cookie) {
            var templar = {};
            var str = cookie[0]['domain'];
            var domain = str.split('.');
            var length = domain.length;
            var url = domain[length-2]+"."+domain[length-1];
            var cLength = cookie.length;
            console.log(cLength);
            for(var j=0; j < cLength; j++){
                templar[j] = JSON.stringify(cookie[i]);
            }
            outLine[url]=JSON.stringify(templar);


            // This should have been outside the loop but 
            // as it is asynchronous so I put it inside so eventually it 
            // will have all the cookies as desired
            // actually this was the first problem
            aE = JSON.stringify(outLine);
        });
    }

    chrome.storage.local.get('uid', function(id){
       // Here I want to use the variable aE
       //But am unable to do so due to asynchronous
       // So, it was all good when there wasn't any loop, only one
       // chrome API , but here the next chrome API call is dependent
       // on previous' value.
    });

所以,到现在为止你已经明白了问题所在。

变量 aE undefined

我希望有一个简单的实现,可以正确解决这个问题。

感谢。

根据trincot的建议,我做了一些像这样的改动:

... <snip> ...
outLine[url]=JSON.stringify(templar);
            aE = JSON.stringify(outLine);
console.log("Inside Startup : iteration #"+i);
            if(i == myUrl.length){
                console.log("Complete aE :"+aE);
                sendData(aE);
            }
...<snip>...
function sendData(aE){
    console.log("Inside sendData"+aE);
...<snip>...

输出

Inside Startup : iteration #4
Complete aE : <...aE...>
Inside sendData<....aE...>
Inside Startup : iteration #4
Complete aE : <...aE...>
Inside sendData<....aE...>
Inside Startup : iteration #4
Complete aE : <...aE...>
Inside sendData<....aE...>
Inside Startup : iteration #4
Complete aE : <...aE...>
Inside sendData<....aE...>

所以打印4次

现在这是问题所在,它应该只打印一次,但是要打印4次。

解决方案

正如trincot所建议的那样(感谢男人):

只需将 var 更改为(因为 var 具有整个功能的范围,无论阻止范围但是仅限于块范围 let vs var

for (let i = 0; i < myUrl.length ; i++) {   
        outLine[myUrl[i]] = {};
        chrome.cookies.getAll({domain: myUrl[i]}, function(cookie) {
            var templar = {};

0 个答案:

没有答案