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