检测浏览器关闭/导航到其他页面并注销的最佳方法
我正在 GWT 中编写一个应用程序,我需要检测用户何时离开我的应用程序或何时关闭浏览器窗口(onUnload 事件)并执行注销(会话失效和其他一些清理任务)。 注销操作由 servlet 执行。
我目前正在通过挂钩 onUnload() 事件并打开一个指向注销 servlet 的新窗口来执行此操作。
有一个更好的方法吗? 欢迎任何其他建议。
I am writing an application in GWT and I need to detect when a user navigates away from my application or when he closes the browser window (onUnload event) and do a logout (session invalidation and few other cleanup tasks). The logout action is performed by a servlet.
I am currently doing this by hooking into the onUnload() event and opening a new window pointed to the logout servlet.
Is there a better way to do this? Any other suggestions are welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看来 GWT 确实有一个专门针对此问题的活动。
ClosingEvent< /a>.
看起来您需要实现 ClosingHandler
Looks like GWT does have an event for exactly this.
ClosingEvent.
Looks like you need to implement a ClosingHandler
为什么不直接创建一个生命周期非常短的会话 cookie,并在每次页面加载时重置,然后添加一个跟踪 cookie。 当用户返回时,您会注意到跟踪 cookie,但没有会话 cookie。 使会话过期并清除所有内容。
当弹出窗口阻止程序阻止 onUnload 窗口打开时,它会阻止您的会话清理,因为这是垃圾邮件发送者使用的东西。
Why not just make a very short lived session cookie that is reset with each page load, then add a tracking cookie. When the user returns you notice the tracking cookie but no session cookie. Expire the session and clear everything up at that point.
Pop up blockers will prevent your session clean up when it blocks the onUnload window open, because this is something spammers use.
这就是关闭事件的工作原理:
然后 GWT 让用户有机会说“是”或“否”。 当然,您也可以在其中添加一个测试,看看他们是否有任何未保存的数据或您想要的任何内容。 不设置消息或将其设置为 null 不会执行任何操作。
This is how the closing event works:
Then GWT gives the user a chance to say yes or no. Of course you can also add a test in there to see if they've got any unsaved data or whatever you want. Not setting the message or setting it to null doesn't do anything.
做到这一点的方法是使用 Window.addWindowClosingHandler ,就像 @Carnell 和 @BillLyons 所说的那样。 但我使用了另一种技术来检测浏览器是否已关闭或页面是否被再次访问(通过刷新或返回导航)。
下面有一个实用程序类可以帮助您。 只需在
onModuleLoad
中调用以下几行即可进行测试。使用示例:
实用程序类:
The way to do that is to use the
Window.addWindowClosingHandler
like @Carnell and @BillLyons said. But I use an additional technique to detect if the browser has been closed or if the page is being visited again (by refresh or back navigation).Following there's an utility class that can help you. Just call the lines below in your
onModuleLoad
to test.The use example:
The utility class: