如何在asp.net中检测服务器端浏览器关闭?
我想知道 asp.net 2.0 中服务器端的浏览器何时关闭。如何检测隐藏代码?
I wanted to know when the browser is closed at server side in asp.net 2.0. How to detect in code behind?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简短的回答:你不能直接这样做,因为 http 是无状态的。也许您可以使用一些 AJAX 心跳池、会话超时检测和其他技巧。
请查看此问题以获取更多说明和想法。这是基于 Java 的,但想法与语言无关。
Short answer: you can't do that directly since http is stateless. Perhaps you can use some AJAX hearbeat pooling, session timeout detection and other tricks.
Take a look at this question for more explanation and ideas. This is Java based, but ideas are language agnostic.
客户端脚本:
服务器端脚本(browserheld.aspx):
client side script:
server side script (browserclosed.aspx):
首先想到的是,您挂钩卸载事件并异步回发浏览器导航离开您的站点(关闭窗口)。然而,使用 HTTP 构建无状态网站的方式使得这变得不可行。您只是没有可靠的方法来跟踪用户连接。
考虑一下您将如何处理多个会话?如果我在多个选项卡或窗口中打开同一个网站,然后关闭除一个之外的所有选项卡或窗口,您如何判断我仍然处于连接状态?有趣的是,假设我的浏览器在中间的某个地方崩溃了。
问题是,我可以设计一些东西来解决你的问题。然而,它永远不会可靠,因为 HTTP 没有内置的连接控制机制。
我必须回答这个问题,并提出一个后续问题。为什么需要知道浏览器窗口何时关闭?
如果您需要进行一些资源清理,有两个服务器端事件,由 ASP.NET 提供便利,您可以更可靠地使用它们。这就是
Session_End
或Application_End
。The first thing that comes to mind is that you hook the unload event and just asynchronously post back that the browser navigated away from your site (closed the window). However, the way that HTTP is being used to build stateless web sites makes this infeasible. You just don't have a reliable way of tracking user connectivity.
Just consider how would you handle multiple sessions? If I have the same site open in many and several, tabs or windows and close down all but one how do you tell that I'm still connected? And for the fun of it, say that my browser crashed somewhere there in between.
The thing is, I could design something that would sort of solve your problem. However, it's never going to be reliable because HTTP doesn't have a built-in control mechanism for connectivity.
I have to answer this question, with a follow up question. Why do you need to know when the browser window closes?
If you need to do some resource clean up there's two server side events, facilitated by ASP.NET that you could use more reliably. And that's
Session_End
orApplication_End
.一个非常明显的问题是为什么你需要这个?您想存储注销时间还是关闭时间?那么最好捕获会话超时。如果您想重定向其他页面,那么最好捕获 javascript 的页面卸载事件。
The quite obvious question is why do you need this? Do you want to store logout time or closing time? Then its better to catch in session timeout. Do you want to redirect some other page then its better to catch in page unload event of javascript.