1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5function validateLinks(links, callback) {
6  var results = [];
7  var pendingRequests = 0;
8
9  function fetchLink(link) {
10    if (!/^http(s?):\/\//.test(link.href))
11      return;
12    var xhr = new XMLHttpRequest();
13    xhr.open("HEAD", link.href, true);
14    xhr.onreadystatechange = function() {
15      if (xhr.readyState < xhr.HEADERS_RECEIVED || xhr.processed)
16        return;
17      if (!xhr.status || xhr.status >= 400) {
18        results.push({
19            href: link.href,
20            text: link.text,
21            status: xhr.statusText
22        });
23      }
24      xhr.processed = true;
25      xhr.abort();
26      if (!--pendingRequests) {
27        callback({ total: links.length, badlinks: results });
28      }
29    }
30    try {
31      xhr.send(null);
32      pendingRequests++;
33    } catch (e) {
34      console.error("XHR failed for " + link.href + ", " + e);
35    }
36  }
37
38  for (var i = 0; i < links.length; ++i)
39    fetchLink(links[i]);
40}
41
42chrome.extension.onRequest.addListener(function(request, sender, callback) {
43  var tabId = request.tabId;
44  chrome.tabs.executeScript(tabId, { file: "content.js" }, function() {
45    chrome.tabs.sendRequest(tabId, {}, function(results) {
46      validateLinks(results, callback);
47    });
48  });
49});
50