I've written a script in JavaScript to check if a clicked link is valid or not The script basically does the following
- intercept all link clicks
- check if they are nested under
a[href]
tags - check if it has a certain text in the url, else allow the link
- check if that URL is working
I want the click to be blocked if the URL 404s or something
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;
Now It's not working and I sense that something is wrong at ajaxurl
init and the reader.open
with ajaxurl
and maybe the return false
part as well. But I just can't see the whole thing clearly yet. I'm quite new to JavaScript, so can you guys help me out?
EDIT/CLOSING QUESTION Thanks to @Louy and @epascarello the code is complete.
// ==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;