0
var k=-1
var j=-1
var data={}
var data_h={}
var finish=false

chrome.webRequest.onBeforeSendHeaders.addListener(
    function(details) {
        j++;
        console.log('BeforeSendHeaders',j)
        console.log(finish)
        if(finish==false){
        //{ console.log('head')
        an=details.requestHeaders[1].value


        data_h[j]=an
        console.log(data_h)
        }   
    }
    , {
        urls: ["https://mms.pinduoduo.com/sydney/api/goodsDataShow/queryGoodsSpanDateList"]
    },
    ["blocking", "requestHeaders", "extraHeaders"]

)

 chrome.webRequest.onBeforeRequest.addListener(


    function(details)
    {
        k++;
        console.log('beforerequest',k)

        if(finish==false)
        {

        buffer=details.requestBody.raw[0].bytes     
        console.log(buffer)  
        var blob = new Blob([buffer]);
//将 Blob对象 读成字符串
        var reader = new FileReader();
        reader.onloadend = function (e) {
        setTimeout(function(){ var send=reader.result; //a Hello world!
                console.log(k,"次")

        data[k]=send}, 1);          
        }
        reader.readAsText(blob, 'utf-8');           
        }

        //} 
    },
    {urls: ["https://mms.pinduoduo.com/sydney/api/goodsDataShow/queryGoodsSpanDateList"]},
    ['requestBody']
); 

chrome.webRequest.onBeforeSendHeaders.addListener(
    function(details) {



        for (var j = 0; j < details.requestHeaders.length; ++j) {
            if (details.requestHeaders[j].name === 'Origin')
                details.requestHeaders[j].value = 'https://mms.pinduoduo.com';
        }



    }, {
        urls: ["https://mms.pinduoduo.com/sydney/api/goodsDataShow/queryGoodsSpanDateList"]
    },
    ["blocking", "requestHeaders", "extraHeaders"]

)

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

    sendResponse({head:data_h,body:data});
});

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// This code gets the requestbody and the request head and send them to content.js. The console prints 'k' start from 1,but not 0.I don't know why the first time filereader.onload doesn't execute the first time. I tried that console.log(buffer) can print correctly,but console.log(k,"次") is not.I guess that it's only because of reader.onload

天气君
  • 87
  • 2
  • 9
  • So your second request is not waiting for the first one to complete before executing? Are you sure you got only one `k` being logged? Could very well be simply that at the time the async code of the first request executes `k` has already been incremented by the second one. – Kaiido Nov 22 '19 at 13:37
  • Suspect https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example/750506 – Kaiido Nov 22 '19 at 13:40

0 Answers0