使用JavaScript检测指向不存在的网站的链接

时间:2013-01-20 07:29:07

标签: javascript

我试图使用JavaScript检测网页上的损坏链接,但我遇到了问题。有没有办法使用客户端JavaScript检测不存在的URL,如下所示?

function URLExists(theURL){
    //return true if the URL actually exists, and return false if it does not exist
}

//test different URLs to see if they exist
alert(URLExists("https://www.google.com/")); //should print the message "true";

alert(URLExists("http://www.i-made-this-url-up-and-it-doesnt-exist.com/")); //should print the message "false";

1 个答案:

答案 0 :(得分:4)

由于Same Origin Policy,您需要在服务器上创建代理才能访问该网站并发回其可用性状态 - 例如使用curl:

<?PHP

$data = '{"error":"invalid call"}'; // json string
if (array_key_exists('url', $_GET)) {
  $url = $_GET['url'];
  $handle = curl_init($url);
  curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

  /* Get the HTML or whatever is linked in $url. */
  $response = curl_exec($handle);
  $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
  curl_close($handle);

  $data = '{"status":"'.$httpCode.'"}';

  if (array_key_exists('callback', $_GET)) {

    header('Content-Type: text/javascript; charset=utf8');
    header('Access-Control-Allow-Origin: http://www.example.com/');
    header('Access-Control-Max-Age: 3628800');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

    $callback = $_GET['callback'];
    die($callback.'('.$data.');'); // 
  }
}
// normal JSON string
header('Content-Type: application/json; charset=utf8');
echo $data;

?>

现在,您可以使用要测试的URL调用该脚本,并以JSON或JSONP调用的形式读取返回的状态


我找到的最好的仅限客户端的解决方法是加载网站的徽标或图标并使用onerror / onload,但这并不告诉我们是否缺少特定页面,只有在网站关闭或已删除其图标时/标志:

function isValidSite(url,div) {
  var img = new Image();
  img.onerror = function() { 
     document.getElementById(div).innerHTML='Site '+url+' does not exist or has no favicon.ico';
  } 
  img.onload = function() { 
    document.getElementById(div).innerHTML='Site '+url+' found';
  } 
  img.src=url+"favicon.ico";
}

isValidSite("http://google.com/","googleDiv")