How to detect browser close at server side in asp.net?

℡╲_俬逩灬. 提交于 2020-01-21 11:06:29

问题


I wanted to know when the browser is closed at server side in asp.net 2.0. How to detect in code behind?


回答1:


client side script:

< body onbeforeunload="window.open('http://www.website.com/browserclosed.aspx','mywindow','width=1,height=1');">

server side script (browserclosed.aspx):

// page_load

int userId = Convert.ToInt32(request.session("userId"));
ReportBrowserClosed(userId);
// Do what you want in ReportBrowserclosed() method



回答2:


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.




回答3:


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 or Application_End.




回答4:


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.



来源:https://stackoverflow.com/questions/4333152/how-to-detect-browser-close-at-server-side-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!