stop redirecting page if it is redirecting by clicking on anchor

javascript, jquery

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;
    });
});

Problem

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?

Original source

Related problems