简体   繁体   中英

Invoke code-behind method when browser is closing

I need to find a way to intercept browser closing and invoke a metod to update a record with several information about logged user in DB. It's very important this record is updated when the user is logging-out or when he close the browser. Obviously when the user clicks 'Logout' I handle the update in the server-side event, but what if the user simply exit from browser?

Someone suggest to use the window.onbeforeunload event and make an asynchronous call to some WS or WebMethod to execute the code, but this doesn't convince me at all: the problem with onbeforeunload is that it shows a confirm prompt. I need to avoid this message and simply invoke the method.

So I'm wondering if there is a 'server-side' solution without using ajax or javascript. For example... a way to trigger some event on session abandon or session clear, or some other way to solve this problem just working on code-behind...

您不可能有一个服务器端解决方案来了解客户端浏览器中发生的事情。

I do not believe there is any way to do what you need server-side only. Client side is the only way. Server has no way of knowing when browser window was closed, this is limitation of HTTP protocol.

Yes, you can put an event in the Global.AsaX which will fire when the session ends. Now if you need data from the client to update the db etc., you'll need a way of getting it there, but if not, then the Session_End will do the trick.

Note: Session end is slightly different than the browser closing, so it this will depend on what you want the event firing to do.

How to handle session end in global.asax?

I'd like to find a 'server-side' solution without using ajax or javascript.

I suspect that it's impossible with that requirement.

Maybe you could do something like:

  1. Have a hidden IFRAME on the page
  2. Set the Refresh header on this IFRAME (or use a META element) to contact the server every couple of seconds
  3. If you do not hear from the client for some period of time, assume the browser has been closed.

However, I imagine that this solution will not scale well.

Have you considered something like signalr? I use it to detect when someone has a record open.

public class ChatHub : Hub
{
     public override Task OnDisconnected()
     {
         Broadcaster.Disconnected(Context.ConnectionId);
         return base.OnDisconnected();
     }
}

For the moment I changed radically the approach to my problem. To update pending rows I implemented a timed job using Quartz.NET framework, that runs every night.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM