用于检查网址是否存在的Javascript

时间:2015-12-29 19:46:24

标签: javascript ajax greasemonkey userscripts

我用JavaScript编写了一个脚本来检查点击的链接是否有效 该脚本基本上执行以下操作

  • 拦截所有链接点击
  • 检查它们是否嵌套在body标记
  • 检查网址中是否有某个文字,否则请允许链接
  • 检查该网址是否有效

如果网址为404或其他内容,我希望阻止点击

a[href]

现在它无法正常工作,我感觉function iClicked(event) { var link = event.target; //go up the family tree until A tag while (link && link.tagName != 'A') { link = link.parentNode; } if (link) { var url = link.href; var ajaxurl = link.getAttribute('href'); var needToCheck = url.indexOf('speed') != -1; //check if the url has the string 'speed' in it if (needToCheck) { var reader = new XMLHttpRequest(); //asynchronous is true reader.open('get', ajaxurl, true); //check each time the ready state changes //to see if the object is ready reader.onreadystatechange = checkReadyState; function checkReadyState() { if (reader.readyState === 4) { //check to see whether request for the file failed or succeeded if ((reader.status == 200) || (reader.status === 0)) { //page exists - redirect to the clicked url document.location.href = url; } else { //if the url does not exist alert("No use going there!"); return false; } } } } } return true; } //intercept link clicks document.onclick = iClicked; 初始化和ajaxurlreader.open以及ajaxurl部分有问题。但我还是不能清楚地看到整件事。我对JavaScript很陌生,所以你们可以帮助我吗?

编辑/结束问题 感谢@Louy和@epascarello,代码已经完成。

return false

1 个答案:

答案 0 :(得分:1)

因为@epascarello说你不能在异步回调中使用return。您需要稍后打开链接。

此外,请记住,您无法在新标签中打开链接。 You'll have to open it in a new window or the same window. There's just no way around that.

如果您仍想这样做,请按以下方式进行:

if (!link) return true;

var url = link.href;
var ajaxurl = link.getAttribute('href');
var needToCheck = url.indexOf('speed') != -1;
//check if the url has the string 'speed' in it
if (!needToCheck) return true;

var reader = new XMLHttpRequest();
//asynchronous is true
reader.open('get', ajaxurl, true);
//check each time the ready state changes
//to see if the object is ready
reader.onreadystatechange = checkReadyState;

function checkReadyState() {
  if (reader.readyState === 4) {
    //check to see whether request for the file failed or succeeded
    if ((reader.status == 200) || (reader.status === 0)) {
      //page exists - redirect to the clicked url
      document.location.href = url;
      // or 
      // window.open(url)
    } else {
      //if the url does not exist
      alert("No use going there!");
    }
  }
}

return false;