Gmail 样式的退出消息
我意识到这可能是重复的,但我已经用谷歌搜索/搜索了一天,但找不到满意的答案。如果 SO 上已有答案,请发送给我。
我有一个客户坚持要求弹出退出消息,确认他们想要退出该网站,就像 Gmail 一样。 (我已经尝试过反对它。他一动不动,所以请不要评论这是一种不好的做法。)
我找到了这段代码:
<script>
window.onbeforeunload = function() {
return 'Are you sure you want to exit?';
}
<script>
但无论我做什么它都会运行 - 重新加载页面,单击导航等等。
我只想在用户关闭选项卡/浏览器时显示该消息。我怀疑这是我错过的一些简单的东西,但我不是 Javascript 专家。
任何帮助将不胜感激。
谢谢
编辑
这是工作得很好的。感谢大家!
var isLeavingSite = true;
//This would be called on each link/button click that navigates
$('a, input[type="submit"]').click(function(){
isLeavingSite = false;
});
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
I realize this is likely a duplicate, but I've been googling/SOing for a day now and I can't find a satisfactory answer. If there is an answer already on SO, please send me there.
I have a client that insists on having an exit message popup confirming they want to exit the site, just like Gmail does. (I've already tried arguing against it. He is immovable, so no comments about how that is bad practice please.)
I've found this code:
<script>
window.onbeforeunload = function() {
return 'Are you sure you want to exit?';
}
<script>
But it runs no matter what I do - reloading the page, clicking on the nav, etc.
I just want the message to show up when the user closes the tab/browser. I suspect it's something simple I'm missing but I'm not a Javascript expert.
Any help would be greatly appreciated.
Thanks
EDIT
Here's what is working pretty good. Thanks to all!
var isLeavingSite = true;
//This would be called on each link/button click that navigates
$('a, input[type="submit"]').click(function(){
isLeavingSite = false;
});
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
虽然这可能是相当大量的工作(取决于您的网站的编写方式),但您可以执行以下操作(伪代码):
如果您使用 jQuery,则可以使用下面的代码来翻转
isLeavingSite
标志:Though it could be a fair amount of work (depending on how your site is written), you could do something like this (pseudo-code):
If you're using jQuery, you can use the code below to flip the
isLeavingSite
flag:所要做的就是使用您在网站上单击任何链接时设置的变量,然后在 onbeforeunload 事件中检查该变量是否设置意味着他们点击了链接或未设置含义他们正在关闭标签。
您还可以使用该变量来简单设置链接的 href;这将允许您检查他们在
onbeforeunload
事件中单击的链接,并允许您检查他们是否单击链接转到您网站上的另一个页面或单击外部链接到另一个网站。What'll have to do is make use a variable that you set if any link is clicked on the site, then inside the
onbeforeunload
event check if that variable is set meaning they clicked a link or not set meaning they're closing the tab.You can also use that variable to simple set the href of the link; that will allow you to then check what link they clicked on inside the
onbeforeunload
event and allow you to check if they're clicking on a link to go to another page on your site or clicking on an external link to another site.如果您使用 jQuery,请尝试退出前确认
If your using jQuery try this Confirm before exit