2014-01-18 46 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