How to prevent calling onbeforeunload when page refresh

There are two things to consider. (1) The "window.onbeforeunload" function executes when the f5 key is released (onkeyup). Anything to modify the dialogue appearance must occur before that as onkeydown. (2) The function will not work if return is followed by a null value.

If you set a global variable to use as a return value AND make it null if the f5 key is pressed, the dialog does not appear when f5 is used to refresh. It does however appear if the "Close" button is pressed. Note that the code inside "onbeforeunload" will run even if the return value is null so you must check for your return value if you want the code to be disabled also.

document.onkeydown = KeyCheck;
window.returnMessage="You are now logged out.";
function KeyCheck(e) {
    var key = (window.event) ? event.keyCode : e.keyCode;
    alert(key);
    if(key==116) {window.returnMessage=null;}
    }
$(function(){
    window.onbeforeunload = function(event) {
        if(window.returnMessage.length > 0) {logoutFunction();}
        return window.returnMessage;
        }   
    });

For what you are looking for, the best way to have control refreshing the webpage would be with the onKeyDown function. Unfortunately pressing the refresh button directly from your browser will load the DOM again, so technically there's no way to prevent the refresh from this action.

Getting into the same issue, I found this webpage http://asquare.net/javascript/tests/KeyCode.html where you can verify the response of your browser to keyboard events. Here you can start figuring out why is onKeyDown the best option. Chrome doesn't react with the onKeyPress function.

You just need a variable to control the refreshing action. If the user presses the key, then the onBeforeUnload action won't be executed.

var refresh = false;  //Control variable to control refresh access
j$(window).bind('beforeunload', function(){
    if (refresh == false) { // If F5 is not pressed
        return "Do you really want to leave?";
    }
});

j$(window).keydown(function(event) {
  if (event.keyCode == 116) { // User presses F5 to refresh
     refresh = true;
   }
});

You can't. A page refresh is like navigating away and unloading the DOM so the onbeforeunload event will always be called.

Tags:

Jquery