0

This stopLeave func. is assigned to 'onbeforeunload' event. What do i do to stop page from refreshing or closing explorer when user press cancel??

Javascript

    function stopLeave(){
    var a = confirm('are you sure you want to leave? you have unsaved work');
    if (a){
         what do i write here? } else
      {   what do i write here?
           }
     }
Parminder
  • 191
  • 2
  • 3
  • 14
  • You should definetely show more code here... – Francisco Presencia Dec 14 '13 at 12:55
  • 1
    You can never hinder the user to leave the page, you can only remind him that it might be not wise. – Bergi Dec 14 '13 at 12:57
  • i have no idea what code should be written in if..else block.. i've searched but no clear response.. – Parminder Dec 14 '13 at 12:57
  • 1
    possible duplicate of [How to show the "Are you sure you want to navigate away from this page?" when changes committed?](http://stackoverflow.com/questions/1119289/how-to-show-the-are-you-sure-you-want-to-navigate-away-from-this-page-when-ch) – Francisco Presencia Dec 14 '13 at 12:57
  • @bergi what shud I do when user does not wants to leave. how do i stop browser to not complete the action.. – Parminder Dec 14 '13 at 12:59
  • return confirm('are you sure you want to leave? you have unsaved work'); – Kamlesh Dec 14 '13 at 12:59
  • @kamlesh when I refresh the page it shows the confirm box.. but when i press cancel it again refreshes the page.. how do i stop browser to cancel the request – Parminder Dec 14 '13 at 13:06

3 Answers3

0

Just return the question string:

window.onbeforeunload = function() {
    return "Are you sure you want to leave? you have unsaved work";
}
0

You can't prevent a user from closing a page. All you can do is allow the browser to ask the user if he wants to leave, like this:

$(window).on('beforeunload', function() { return 'are you sure you want to leave? you have unsaved work'; });
pvgoran
  • 442
  • 3
  • 14
0

Try this if you do it with vanila javascript and need to ensure cross-browser compatibility:

function stopLeave(e){
    var message = 'Are you sure you want to leave?'; 
    var e = e || window.event;
    if (e) {
        e.returnValue = message ;
    }
    return message;
}
Khanh TO
  • 48,509
  • 13
  • 99
  • 115