简体   繁体   中英

stop redirecting page if it is redirecting by clicking on anchor

I want to prevent page redirecting I know it can be achieve by this

window.onbeforeunload = function() {
        return "Dude, are you sure you want to leave? Think of the kittens!";
}

which was answered here Prevent any form of page refresh using jQuery/Javascript

But in my case I only want to prevent page when it is redirecting by clicking on any of the anchor tag.

Also event.preventDefault() will not work in my case while clicking on anchor tag because all anchors are not redirecting page so it should work fine.

I only want to stop redirecting page if it is redirecting by clicking on anchor. Any solution?

You can keep a flag which tells you whether or not the user clicked an a tag, then read that on your onbeforeunload script:

window.onbeforeunload = function () {
    if (_clickedAnchor) {
        _clickedAnchor = false;
        return "Dude, are you sure you want to leave? Think of the kittens!";
    }
}

_clickedAnchor = false;

jQuery(document).ready(function () {
    jQuery("a").click(function () {
        _clickedAnchor = true;
    });
});

You can use onhashchange .

With jQuery:

$(window).on('hashchange', function() {
    alert('bye byee?');
});

Plain DOM JavaScript:

window.onhashchange = function() {
    alert('bye byee?');
};

Note: You will need to create a custom "hash-change" handler for older browser which don't support this event.

You can easly do this with setInterval and detect any changes in document.location.hash .


Failsafe onhashchange for older browsers:

var currentHash = document.location.hash;

window.prototype.onhashchange = function( callback ) {
    if(typeof(callback) == 'function') {
        setInterval(function() {
            if(document.location.hash !== currentHash) {
                callback();
            }
        }, 650); // more than a half-a-second delay
    }
}

And you can use it as an event in regular DOM convention.

So since you tagged jQuery I'll put my solution in terms of that. You can grab all the a tags and then check to make sure the anchor is a redirect, then use the e.preventDefault();

$('a').on('click',function(e){
    if ($(this).attr('href') != window.location.href)
    {
       e.preventDefault();
       //do stuff
    }
});

The caller will be null if a link is clicked:

window.onbeforeunload = function() {
    alert(window.onbeforeunload.caller)    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM