0

I have some actions being performed on my website and I don't want people leaving or reloading accidentally before all actions are done. This is pretty straight forward but when all the actions are done I don't want them seeing the warning (I want them just to get redirected).

I followed Warn user before leaving web page with unsaved changes and few others but that last part (no warning when everything is done, certain variable set to true).

So this is what I got:

Here the variable that was previously set gets the value true after all actions are done. (This works fine)

do_redirect = true;
window.location.href = "some url";

Now this is the part where I get the leave/reload warning:

do_redirect = true;
window.addEventListener("beforeunload", function (e) {
    if (do_redirect) {
        console.log("ITS TRUE")
        return undefined;
    }
    console.log(do_redirect);
    var confirmationMessage = 'If you leave, you are not going to be able to come back';

    (e || window.event).returnValue = confirmationMessage; //Gecko + IE
    return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
});
<button onclick="do_redirect = false;">Create unsaved work</button>
<button onclick="do_redirect = true;">Save work</button><br/>
<button onclick="location.href = 'data:text/plain,You were redirected!';">Try leaving</button>

So the regular user leave/reload works perfectly but the problem occurs when I (the website) wants to redirect users to another page. I'm not sure what the problem here is.

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51

0 Answers0