防止刷新时调用 onbeforeunload()
我有一个网页,当用户关闭选项卡或浏览器时,我会销毁会话。这是我的脚本:
window.onbeforeunload = function() {
document.write("<?php session_destroy();
?>");
}
我的问题是我只想在浏览器关闭时销毁会话。我应该使用哪个事件?这在所有浏览器中都可能吗?请帮忙。
I have a web page where I am destroying the session when the user closes the tab or browser. This is my script:
window.onbeforeunload = function() {
document.write("<?php session_destroy();
?>");
}
My problem is I want to destroy the session only when the browser is closed. which event should i use? Is this possible in all browsers? Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,当浏览器关闭时,会话将被销毁。这实际上是由 PHP 配置选项
session.cookie_lifetime
控制的。 来自 PHP 手册:您想要做的,当浏览器关闭时显式销毁服务器端的会话数据,是无法完成的。无法判断(至少从 Javascript)页面是否正在重新加载或浏览器是否正在关闭 - 这两个事件都会触发
onunload()
和onbeforeunload()
同样的方式。另一点是,它会涉及在浏览器关闭时向服务器发送请求,这是极不可能被允许的并且不能依赖 - 毕竟,如果服务器无法响应怎么办?这可能会导致浏览器挂起等待响应,这会破坏用户体验,浏览器开发人员永远不会允许这种情况发生。
Sessions are destroyed when the browser closes by default. This is actually controlled by the PHP configuration option
session.cookie_lifetime
. From the PHP manual:What you are trying to do, explicitly destroy the session data at the server side when the browser is closed, cannot be done. There is no way to tell (from Javascript at least) whether the page is being reloaded or the browser is being closed - both events fire
onunload()
andonbeforeunload()
in the same manner.The other point about this is that it would involve sending a request to the server as the browser closes, which is highly unlikely to be allowed and could not be relied upon - after all, what if the server failed to respond? It could result in the browser hanging on close waiting for a response, which would ruin the user experience and the browser developers would never allow it.