简体   繁体   English

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

[英]Detect links to non-existent websites using JavaScript

I'm attempting to detect broken links on a web page using JavaScript, and I've run into a problem. 我正在尝试使用JavaScript检测网页上的损坏链接,但遇到了问题。 Is there any way to detect non-existent URLs using client-side JavaScript, as seen below? 有什么方法可以使用客户端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";

Due to Same Origin Policy , you would need to create a proxy on a server to access the site and send back its availability status - for example using curl: 由于同源策略的缘故,您需要在服务器上创建代理以访问站点并发送其可用性状态(例如,使用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;

?>

Now you can ajax to that script with the URL you want to test and read the status returned, either as a JSON or JSONP call 现在,您可以使用要测试的URL来对该脚本进行Ajax,并以JSON或JSONP调用的形式读取返回的状态


The best client-only workaround I have found, is to load a site's logo or favicon and use onerror/onload but that does not tell us if a specific page is missing, only if the site is down or have removed their favicon/logo: 我发现最好的仅客户端解决方案是加载站点的徽标或图标,并使用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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM