javascript 在浏览器/选项卡关闭时终止会话
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4508390/
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
Kill sessions on browser/tab close
提问by Carlos Mora
I've been trying to solve how to close session when browser/tab is closed. Following the Daniel Melo's answer + setting session's coockie TTL to 0 i'm almost ready, but Daniel's tip is not working for input type=[button].
我一直在尝试解决如何在浏览器/选项卡关闭时关闭会话。按照 Daniel Melo 的回答 + 将 session 的 coockie TTL 设置为 0 我几乎准备好了,但 Daniel 的提示不适用于 input type=[button]。
var validNavigation = false;
function endSession() {
document.cookie = 'MYOWNSESSID=; path=/';
}
function okEvent(){
validNavigation = true;
}
function wireUpEvents() {
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
$("a").bind("click", okEvent );
$("form").bind("submit", okEvent );
// that's my adds that don't work
$(":button").bind("click", okEvent );
$(":button").bind("submit", okEvent );
$(":button").onclick= okEvent;
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
The key if to flag an event as valid before unloading occurs. I'm trying to hook the buttons click but without success. The jquery selector is working fine, i checked that $(':button').length is > 0. Sure i'm missing something but can't find it.
在卸载发生之前是否将事件标记为有效的关键。我试图挂钩按钮点击但没有成功。jquery 选择器工作正常,我检查了 $(':button').length > 0。当然我遗漏了一些东西但找不到它。
回答by ifaour
Ok, here are some tips:
好的,这里有一些提示:
-replace the three lines you've added with:
- 替换您添加的三行:
$(':button').click(okEvent);
-Don't bind the submit event on a Button input, not to be confused with the Submit input (more):
- 不要在按钮输入上绑定提交事件,不要与提交输入混淆(更多):
<input type="submit" value="Submit" />
-if you are using the Button to submit the form, then use the submit input instead and remove all your additions since the submit event is already attached to the form:
- 如果您使用 Button 提交表单,请改用提交输入并删除所有添加项,因为提交事件已附加到表单:
$("form").bind("submit", okEvent );
Please check thistest to better understand the Button input.
请检查此测试以更好地理解按钮输入。

