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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With