Search code examples
asp.nethttponunloadstateless

Is there a way using ASP.NET to always run some server side code when a user leaves a page?


I was wondering if there is any way to always run some server side code when a user leaves a page in ASP.NET. The page Unload event is no good because that doesn't get called if someone clicks on a link. Ideally I'd also like the code to run even if the user closes the browser.

I suspect what I'm asking isn't possible, but it doesn't hurt to ask


Solution

  • Problem is, HTTP is a stateless protocol, so when the page has finished being served, you wont know if the user is still on the page or not.

    The only way to acheive this would be a hidden piece of Javascript that constantly pings the server with it's session ID, or another similar mechanism. When the ping becomes unresponsive you can reasonably assume the page is not being viewed by the user anymore.

    Here is a diagram that explains traditional HTTP message flow.

    alt text