0
我們有URL的一些列表:以同步方式逐一處理URL列表?
var urls = ['http://google.com','http://yahoo.com','http://yandex.com'];
我們的任務是遍歷的URL列表,然後...
- 創建網址,記得
tabId
- 連接監聽器
chrome.webRequest.onCompleted
與tabId
過濾器 - 等待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)它允許通過使用loop
或next
網址循環,但我們必須做出一些修改,見遞延TUTS。
感謝您的評論。我瞭解你的解決方案。我還發現了另一個使用'Deferred js'對象,請參閱http://cho45.stfuawsc.com/jsdeferred/doc/Deferred.html – Kirzilla