jQuery 窗口关闭事件上的javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16540972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript on window close event
提问by danyo
I am currently detecting if a user of my site closes the window/tab or changes the url.
我目前正在检测我网站的用户是否关闭了窗口/选项卡或更改了 url。
I am using the follwoing code, which works perfectly:
我正在使用以下代码,它完美地工作:
var validNavigation = false;
function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}
function wireUpEvents() {
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
$(document).ready(function() {
wireUpEvents();
});
My problem is i would like to change the event from an alert to a overlay. I have setup up a hidden div overlay and replaced the alert in the above code with:
我的问题是我想将事件从警报更改为覆盖。我已经设置了一个隐藏的 div 覆盖并将上面代码中的警报替换为:
$('.overlay').css('display','block');
This now no longer works, as there is nothing within the div to get the user to stay on the page. (the user doesn't have to click a button within an alert)
这现在不再有效,因为 div 中没有任何内容可以让用户停留在页面上。(用户不必单击警报中的按钮)
Any suggestions on how i can get around this?
关于如何解决这个问题的任何建议?
Cheers, Dan
干杯,丹
采纳答案by Harsh Chunara
The window close event is fired as the very last event. Therefore no other events are fired after it.
窗口关闭事件作为最后一个事件被触发。因此,在它之后不会触发其他事件。
You can use the beforeunload event with Jquery, to show the overlay on screen.
您可以在 Jquery 中使用 beforeunload 事件,以在屏幕上显示叠加层。
The following link could help: link
以下链接可能会有所帮助:link