How to manipulate a link in href

2

Is it possible to treat a link , for example when I click and the page does not exist, I redirect to a specific place?

For a page of "ops this link does not exist" for example.

In my case I'm doing an appWeb (phonegap), where I wanted to redirect the app to another app, if it does not exist redirect to the store.

    
asked by anonymous 05.02.2016 / 18:21

1 answer

2

You can do this with AJAX. You create an ajax call to this url and depending on the answer you know if the url exists, has errors or not. An example would look like this:

function verificar(url, cb) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.onload = function() {
        if (request.status >= 200 && request.status < 400) cb(true);
        else cb(false);
    };

    request.onerror = function() {
        cb(false);
    };
    request.send();
}

var links = document.querySelectorAll('a');
for (var i = 0; i < links.length; i++) {
    links[i].addEventListener('click', verificador(links[i]))
}

function verificador(el) {
    return function(e) {
        e.preventDefault();
        var url = e.target.href;
        var status = verificar(url, function(sucesso){
                alert('Essa página ' + (sucesso ? 'existe!' : 'não existe :('));
        });
    }
}

jsFiddle: link

    
05.02.2016 / 18:50