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

前端 未结 4 1899
情深已故
情深已故 2021-01-18 02:25

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

相关标签:
4条回答
  • 2021-01-18 02:27

    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
    
    0 讨论(0)
  • 2021-01-18 02:29

    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.

    0 讨论(0)
  • 2021-01-18 02:36

    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.

    0 讨论(0)
  • 2021-01-18 02:36

    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.

    0 讨论(0)
提交回复
热议问题