0

我正在尝试从 Chrome 扩展中的 URL(数组)列表中列出所有尚未访问的链接。但是我下面的函数只返回一个 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);
}

参考:争吵异步 chrome.history 调用

4

1 回答 1

3

您可能误解了异步调用的含义(和内部工作原理)。

我会提出以下方法:

  1. 提供要执行的 URL 列表和回调,其中未访问的 URL 列表作为参数(在所有 URL 的历史记录检查完成后)。

  2. 对于原始列表中的每个 URL
    :检查它是否已被访问(如果是,则将其添加到未访问的 URL 列表中)。
    湾。增加一个checkedURLs计数器。
    C。检查是否所有 URL 都已(异步)检查,即checkedURLs等于原始 URL 列表的长度。

  3. 当您检测到所有 URL 都已被检查(参见2.c.)时,执行指定的回调(参见1.),将未访问的 URL 列表作为参数传递。


演示扩展的一些示例代码:

清单.json:

{
    "manifest_version": 2,
    "name":    "Demo",
    "version": "0.0",

    "background": {
        "persistent": false,
        "scripts": ["background.js"]
    },
    "browser_action": { "default_title": "Demo Extension" },
    "permissions": ["history"]
}

背景.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);
});
于 2013-10-27T09:30:45.407 回答