Conditional onbeforeunload event on page

window.onbeforeunload = function(evt) {
    var message = 'Are you sure you want to leave the page. All data will be lost!';

    if (typeof evt === 'undefined') {
        evt = window.event;
    }
    if (evt && !($("#a_exit").click)) {
        evt.returnValue = message;
    }
    return message;
};

I want the user to leave the page by clicking on the link (only id ="a_exit"). In other cases, such as refreshing the page, clicking on another link, the user will be prompted that he / she wants to leave the page. I tried using the code above. He still asks me if I want to leave when I click on the exit link.

+9
source share
6 answers

You can simply delete it window.onbeforeunloadin the click handler.

+2
source
$(window).bind('beforeunload',function() {
    return "'Are you sure you want to leave the page. All data will be lost!";
});

$('#a_exit').live('click',function() {
    $(window).unbind('beforeunload');
});

Over work for me

+4
source
+2

:

    window.onbeforeunload = confirmExit;
    function confirmExit(event) {
        var messageText = tinymce.get('mMessageBody').getContent();
        messageText = messageText.trim();

        // ... whatever you want

        if (messageText != "")
            return true;
        else
            return void (0);
   };

Chrome, FF.

+2

, ?

var exitClicked = false;

$("#a_exit").click(function() {
  exitClicked = true;
});

window.onbeforeunload = function(evt) {
  //...

  if(evt && !exitClicked) {
    evt.returnValue = message;
  }  

  //...
};

exitClicked = true, , , , .

0

It worked for me.

   window.onbeforeunload = function(){
    if(someBoolean) {
    return 'message'
    }else{
    window.onbeforeunload = null;
    }
    }
0
source

All Articles