2015-12-29 2 views
1

Я написал сценарий в JavaScript, чтобы проверить, если щелкнуть ссылку действителен или не сценарий в основном имеет следующийJavascript, чтобы проверить, если URL существует

  • перехватывать все щелкает ссылку
  • проверить, если они вложены в a[href] тегах
  • проверить, если он имеет определенный текст в URL, иначе позволяет по ссылке
  • чека, если что URL работает

Я хочу, чтобы щелчок, чтобы быть заблокирован, если URL ошибки 404 или что-то

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; 

Сейчас он не работает, и я чувствую, что что-то неправильно в ajaxurl инициализации и reader.open с ajaxurl и, возможно, в return false части, а также. Но я просто не могу все ясно видеть. Я совершенно новичок в JavaScript, так что вы, ребята, можете мне помочь?

EDIT/ЗАКРЫТЬ ВОПРОС Благодаря @Louy и @epascarello код завершен.

// ==UserScript== 
// @name  Check before Click 
// @namespace CheckbeforeClick 
// @include  * 
// @version  1 
// @grant  none 
// ==/UserScript== 


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) return true; 

    var url = link.href; 
    var ajaxurl = link.getAttribute('href'); 
    //change the following to apply on other links, maybe regex 
    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!"); 
     } 
     } 
    } 
    reader.send(null); 

    return false; 
} 

//intercept link clicks 
document.onclick = iClicked; 
+1

«проверьте, если что URL работает» , вероятно, не способ сделать это легко в JavaScript. [CORS] (https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) не позволит вам. Вам нужен прокси-сервер или что-то в этом роде. – Louy

+0

Вы не можете вернуть true или false из асинхронного метода. – epascarello

+0

@Louy URL-адреса находятся в samesubdomain. и фактический тег href всегда будет иметь относительные URL-адреса. thats, что я получаю на 'var ajaxurl' – mystupidstory

ответ

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; 
+0

Это сработало, спасибо! Кстати, вы, как и я, забыли вставить фактическую часть 'reader.send': D – mystupidstory