您好我希望当我的网站被任何用户关闭时向用户显示弹出窗口。如何检测此事件。我有一个解决方案,但它不适用于浏览器刷新点击
var exit = true;
$(window).on("keydown",function(e){
if(e.which === 116){
exit = false;
}
});
$(window).bind("beforeunload", function() {
if (exit === true) {
return "Are you sure you want to leave?";
} else {
return;
}
});
答案 0 :(得分:1)
使用以下JavaScript可以非常简单地完成...
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
修改强>
当用户按下浏览器中的刷新按钮时,我不知道如何避免触发此脚本,但是有一种方法可以在按下f5时停止它...
<强>的jQuery 强>
//you need to set the variable exit to true first so it fires when f5 is not pressed
var exit = true;
//on keydown event will check if f5 is pressed
$(window).on("keydown",function(e){//begin window on keydown event
//f5 key code is 116
if(e.which === 116){//begin if it f5 is pressed
//set exit to false so the prompt isn't displayed
exit = false;
}
});
//bind the beforeunload event to the window
$(window).bind("beforeunload", function() {
//if exit = true then display the prompt
if (exit === true) {
//display the prompt
return "Are you sure you want to leave?";
} else {
//do nothing, no prompt will be created
return;
}
});
不要忘记在<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>