Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent calling onbeforeunload when page refresh

Tags:

jquery

I want to prevent calling the function confirmExit() when the page is refreshed. Is it possible to do that?

<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
   $.post("test.php");
}
</script>
like image 543
mymotherland Avatar asked Apr 09 '11 16:04

mymotherland


2 Answers

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;
   }
});
like image 132
edolopez Avatar answered Nov 17 '22 01:11

edolopez


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

like image 17
Darin Dimitrov Avatar answered Nov 17 '22 00:11

Darin Dimitrov