gpt4 book ai didi

javascript - 关闭浏览器时显示警告框,但使用 f5 或浏览器刷新按钮重新加载或刷新页面时不显示警告框

转载 作者:行者123 更新时间:2023-12-03 04:09:05 26 4
gpt4 key购买 nike

您好,我想在我的网站被任何用户关闭时向用户显示弹出窗口。如何检测此事件。我有一个解决方案,但它在浏览器刷新点击时不起作用

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;
}
});

最佳答案

使用以下 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> 中包含 jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

关于javascript - 关闭浏览器时显示警告框,但使用 f5 或浏览器刷新按钮重新加载或刷新页面时不显示警告框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44409419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com