连续调用chrome.extension.sendMessage()

时间:2013-07-21 13:13:32

标签: asynchronous google-chrome-extension storage

我正在写一个扩展程序,我希望自己的Cookie存储mycookies存储在background.js中,它存储域,路径,密钥和标志。在我的background.js中,当收到HTTP响应时,我会为响应的每个Set-Cookie标头调用chrome.extension.sendMessage()。因此,每个响应在几毫秒内多次调用此函数。在响应之后,只存储最后一个或两个cookie,其余的都丢失了。

我做了以下实验。我连接了一个带有update_mycookies功能的按钮。单击按钮立即调用该函数,并在2500ms后显示mycookies的内容。如果我在2500ms之后阅读商店,如果我在update_mycookies中引入延迟(如下所示),那么所有四个cookie都在那里但是如果我删除延迟,则只更新最后一个或两个cookie,其余的都会丢失。 chrome.extension.sendMessage正在使用`chrome.storage.local.set()。我希望我的商店必须更新所有的cookie作为回应。

function update_mycookies(){
    chrome.extension.sendMessage({"cdomain":".google.com", "path":"/", "key":"PREF"});
    setTimeout(function() {
        chrome.extension.sendMessage({"cdomain":".google.com", "path":"/", "key":"NID"});}, 1000);

    setTimeout(function(){
        chrome.extension.sendMessage({"cdomain":".google.it", "path":"/", "key":"PREF"}); }, 1500);

    setTimeout(function(){
        chrome.extension.sendMessage({"cdomain":".google.it", "path":"/", "key":"NID"}); }, 2000);
}

onMessage听众如下:

chrome.extension.onMessage.addListener(  
  function(request,sender,sendResponse) {
 if (request["cdomain"] && request["path"] && request["key"]) {
       chrome.storage.local.get("mycookies", function (items) {
         if (items["mycookies"]) {
          var found = false;
           var entries = items["mycookies"].split(";");
           entries.forEach (function (entry) {
            var dk = entry.split(",");
             if (dk[0] == request["cdomain"] && dk[1] == request["path"] && dk[2] == request["key"])
               found = true; 
           });
           if (!found)
             chrome.storage.local.set({"mycookies": items["mycookies"] + ";" + request["cdomain"] + "," + request["path"] + "," 
               + request["key"] });
         }
        else 
     chrome.storage.local.set({"mycookies": request["cdomain"] + "," + request["path"] + "," + request["key"] });
      }); 
   }
 }

0 个答案:

没有答案