问题
I'm searching for a way to let my users know that they have to log off when they are closing the window. I've already founded this code:
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "It is better if you log out, before you close this page!";
}
$(function ()
{
$("a").click(function()
{
window.onbeforeunload = null;
});
});
This works perfectly when I close my page. just as I want, but it also shows when I reload the page, which shouldn't happen.
Anyone an idea how to solve this, is it even possible?
回答1:
I believe this will help solve your problem. It works by first detecting if the keycode 116 has been pressed by the user(f5 key) or in other words the refresh button. If it has it will store the state of this button press so that the event beforeunload will not display the prompt. Below is the javascript/jquery you will need:
Note: This will not behave as expected in a jsfiddle so I excluded an example.
//set the variable exit to true initially because you haven't hit
//the f5 button yet to refresh
var exit = true;
//on keydown event to check if the f5 or 116 keycode has been pressed
$(window).on("keydown",function(e){//begin window on keydown event
//if the keycode = 116
//in other words the user has pressed the f5 key
if(e.which === 116){//begin if then
//set exit to false because so the prompt doesn't display
exit = false;
}//end if then
});//end window on keydown event
//bind the beforeunload event to the window
$(window).bind("beforeunload", function() {//begin event
//if exit = true then display the prompt
if (exit === true) {//begin if then
//display the prompt
//note the browser may over ride the string in your return value
return "Are you sure you want to leave?";
} else {
//do nothing, no prompt will be created
return;
}//end if then
});//end event
来源:https://stackoverflow.com/questions/27594033/alert-box-when-closing-window-but-not-on-reload