Skip to content Skip to sidebar Skip to footer

Prevent User To Leave My Page In Javascript

In my form, I have an unshowy modal. I open the modal if the user clicks on my 'leave image' and I ask if he wants to leave. Is that possible in JavaScript (Jquery ?) to 'stop' the

Solution 1:

There is no way of stopping user from leaving the page. Only thing that can be done is confirm window.

Solution 2:

There is both window.onbeforeunload and window.onunload, which are used differently depending on the browser. You can ask them either by setting the window properties to functions, or using the .addEventListener:

window.onbeforeunload = function(){
   // Do something
}

// OR

window.addEventListener("beforeunload", function(e){
   // Do something
}, false);

Usually, onbeforeunload is used if you need to stop the user from leaving the page (ex. the user is working on some unsaved data, so he/she should save before leaving). onunload isn't supported by Opera, as far as I know, but you could always set both.

Post a Comment for "Prevent User To Leave My Page In Javascript"