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

Detect links to non-existent websites using JavaScript

本文关键字:不存在 网站 链接 JavaScript 检测 使用      更新时间:2023-09-26

我正在尝试使用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";

由于同源策略,您需要在服务器上创建代理来访问站点并发回其可用性状态—例如使用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对该脚本进行ajax处理,并读取返回的状态,可以是JSON或JSONP调用


我发现的最好的客户端解决方案是加载网站的徽标或favicon并使用onerror/onload,但这并不能告诉我们特定页面是否缺失,只有当网站关闭或删除了他们的favicon/徽标:

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")