我正在尝试列出Chrome扩展程序中的网址列表(数组)中尚未访问过的所有链接。但我的下面的函数只返回一个URL。我在哪里做错了?
function remove_visited(urls, fn) {
var links = urls,
unvisitedUrls = [],
done = false;
console.log(urls);
var checkUrl = function(d) {
var url = d;
console.log(url);
return function(visitItems) {
if (visitItems && visitItems.length > 0) {
unvisitedUrls.push(url);
}
links.splice(links.indexOf(url));
if(links.length <= 0) {
return;
}
}
}
links.forEach(function(d) {
chrome.history.getVisits(d, checkUrl(d));
});
fn(links);
}
答案 0 :(得分:3)
您可能错过了异步调用的含义(和内部工作原理)。
我建议采用以下方法:
提供一个URL列表和一个要执行的回调,其中包含未访问的URL列表作为参数(在完成所有URL的历史记录检查之后)。
对于原始列表中的每个网址:
一个。检查是否已访问过(如果是,请将其添加到未访问的URL列表中)
湾增加一个checkedURLs
计数器
C。检查是否已(异步)检查了所有URL,即checkedURLs
等于原始URL列表的长度。
当您检测到所有网址都已被选中时(请参阅 2.c。),请执行指定的回调(请参阅 1。),并传递列表未经访问的URL作为参数。
演示扩展的一些示例代码:
<强>的manifest.json:强>
{
"manifest_version": 2,
"name": "Demo",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"browser_action": { "default_title": "Demo Extension" },
"permissions": ["history"]
}
<强> background.js:强>
/* List of URLs to check against */
var urlList = [
"http://stackoverflow.com/",
"http://qwertyuiop.asd/fghjkl",
"https://www.google.com/",
"https://www.qwertyuiop.asd/fghjkl"
];
/* Callback to be executed after all URLs have been checked */
var onCheckCompleted = function(unvisitedURLs) {
console.log("The following URLs have not been visited yet:");
unvisitedURLs.forEach(function(url) {
console.log(" " + url);
});
alert("History check complete !\n"
+ "Check console log for details.");
}
/* Check all URLs in <urls> and call <callback> when done */
var findUnvisited = function(urls, callback) {
var unvisitedURLs = [];
var checkedURLs = 0;
/* Check each URL... */
urls.forEach(function(url) {
chrome.history.getVisits({ "url": url }, function(visitItems) {
/* If it has not been visited, add it to <unvisitedURLs> */
if (!visitItems || (visitItems.length == 0)) {
unvisitedURLs.push(url);
}
/* Increment the counter of checked URLs */
checkedURLs++;
/* If this was the last URL to be checked,
execute <callback>, passing <unvisitedURLs> */
if (checkedURLs == urls.length) {
callback(unvisitedURLs);
}
});
});
}
/* Bind <findUnvisited> to the browser-action */
chrome.browserAction.onClicked.addListener(function() {
findUnvisited(urlList, onCheckCompleted);
});