Kill unload function in JS?

Is there a way to kill the unload function using javascript (jquery)?

I am looking for something like this:

window.onbeforeunload = function(){
    confirm("Close?")
}

or in jquery:

$(window).unload(function() {
    confirm("close?")
});

Now, when the window is unloaded, I get my confirmation, but it will continue anyway. By clicking "Cancel", it will not remain on my page.

+3
source share
3 answers

the function must return falseto interrupt or trueto continue, so you can simply confirm the confirmation as follows:

window.onbeforeunload = function(){
   return confirm("Close?")
}
+2
source
$(window).unload(function() {
    var answer = confirm("Leave This website?")
if (answer){
    return false;
}
else{
    alert("Thanks for sticking around!");
    return true;
}
});
+1
source

Yes, there is a way. The onbeforeunload function works a little differently than other events. All you have to do is return a string from this function, and the browser will do all the work for you. The syntax is as follows:

window.onbeforeunload = function () { 
  return "Close?"; 
}

And all you have to do. When you click "Cancel" in the dialog box that appears, the user will be on the current page, and OK will allow the user to go or close the page. It is really simple enough that you do not need to use jQuery at all.

+1
source

Source: https://habr.com/ru/post/1736672/


All Articles