How to manipulate a link in href

Asked

Viewed 219 times

2

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

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

Because in my case I’m doing an appWeb (phonegap), where I wanted to redirect the app to another app, in case it doesn’t exist redirect to the store.

  • It is possible to test with ajax, but with some reservations. This other page is of the same domain?

  • Yes it would be within the same domain

1 answer

2


You can do this with AJAX. You create an ajax call for that url and depending on the answer you know whether the url exists, has errors or not. An example would be 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: https://jsfiddle.net/Sergio_fiddle/djsjx70z/

  • 1

    was of great value this code, I thank the attention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.