2014-01-18 24 views
0

我们有URL的一些列表:以同步方式逐一处理URL列表?

var urls = ['http://google.com','http://yahoo.com','http://yandex.com']; 

我们的任务是遍历的URL列表,然后...

  • 创建网址,记得tabId
  • 连接监听器chrome.webRequest.onCompletedtabId过滤器
  • 等待3秒后最后chrome.webRequest.onCompleted甚至发生
  • 分离听众
  • 继续下一个URL

我需要处理后才以前的URL成功处理每下一个URL。我不需要并行运行它们。

这是可以并行运行的代码。如何修改它以逐一同步的方式运行?

var processURL = function(url) { 

    //var that contains timestamp of last chrome.webRequest.onCompleted event 
    var lastOnCompletedTimestamp = null; 

    //our listeners that will be attached 
    var webRequestListeners = { 
     onCompleted : function(details) { 
      lastOnCompletedTimestamp = new Date().getTime(); 
     } 
    } 

    //method to attach web request listener 
    var attachWebRequestListeners = function(tabId) { 
     chrome.webRequest.onCompleted.addListener(
      webRequestListeners.onCompleted, 
      {urls: [ "<all_urls>" ], types : ["main_frame"], tabId : tabId}, 
      ['responseHeaders']   
     ) 
    } 

    //method to detach web request listener 
    var detachWebRequestListeners = function(tabId) { 
     //Attention: I'm not sure is it possible to detach webRequest listeners 
     //for tabId; I was unable to find any description for that at Chrome Extension API docs 
    } 

    //method 
    var onTabCreated = function(tab) { 
     var tabId = tab.tabId; 
     attachWebRequestListeners(tabId); 
     //when all webRequest listeners are attached we can update tab to go to URL 
     chrome.tabs.update(tabId, {url:url}); 
     var interval = setInterval(function() { 
      if (
       lastOnCompletedTimestamp != null 
       && new (Date().getTime() - lastOnCompletedTimestamp < 3000) 
      ) { 
       //if more that 3 sencods past from last onCompleted event - detach events 
       detachWebRequestListeners(tabId); 
          clearInterval(interval); 

      } 
     }, 200); 
    } 

    //creating empty tab without URL 
    chrome.tabs.create(
     {active: false}, 
     function(tab) { 
      onTabCreated(tab); 
     } 
    ); 

} 

var urls = ['http://www.google.com', 'http://yandex.ru', 'http://.yahoo.com']; 
for(var i in urls) { 
    //this will start all urls in parallel, but I need to wait for execution of one url and only after this go to next one 
    processURL(urls[i]); 
} 

UPD:我发现很不错Deferred js对象(见http://cho45.stfuawsc.com/jsdeferred/#behavior)它允许通过使用loopnext网址循环,但我们必须做出一些修改,见递延TUTS。

回答

1

只有在完成前一个选项卡后,才需要开始处理每个选项卡。这可以通过在前面的选项卡的区间回调结束发起一个标签的处理来实现:

改变这样的代码:

var urls = [...]; 
var processURL = function (idx) { 
    if (idx >= urls.length) { return; } 
    var url = urls[idx]; 
    ... 
    var onTabCreated = function(tab) { 
     ... 
     var interval = setInterval(function() { 
      ... 
      clearInterval(interval); 
      processURL(idx + 1); 
    ... 
}; 
processURL(0); 

BTW,tabId = tab.tabIdshould betabId = tab.id

+0

感谢您的评论。我了解你的解决方案。我还发现了另一个使用'Deferred js'对象,请参阅http://cho45.stfuawsc.com/jsdeferred/doc/Deferred.html – Kirzilla