简体   繁体   中英

Javascript 404 check on anchor tag click

I need to implement javascript only solution that would override default a href behavior, check if href location exist and then redirect to it or to 404.html. So far I come up with this:

function UrlExists(url) 
{
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status!=404;
}

document.onreadystatechange = function() 
{
    var anchorElements = document.getElementsByTagName('a');
    for (var i in anchorElements)
        anchorElements[i].onclick = function() 
        {
        if (UrlExists(this.href)) {window.location=this.href; }
        else {window.location='404.html'=;}
                return false;
            }
}

However, if UrlExists() gets called, default behavior is not overridden. Any ideas?

EDIT: 404 check works, and all links are on same domain Also non jQuery solution is preferred.

//UrlExists function was copied from Trip and jAndy

Thanks to RobM. and Script47 for pointing out that preventDefault is native function:

   function UrlExists(url) 
{
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status!=404;
}

document.onreadystatechange = function() 
{
    var anchorElements = document.getElementsByTagName('a');
    for (var i in anchorElements)
        anchorElements[i].onclick = function(th) 
        {
        th.preventDefault();
        if (UrlExists(this.href)) { window.location=this.href; }
        else {window.location='404.html';}
                return false;
            }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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