Skip to content

Implementing a heartbeat pattern with AJAX and ASP.NET

So I’m working on a web application, where I needed a way to detect when a user has closed their browser.

Javascript’s onunload event looked promising. However, it is unable to differentiate between a browser closing, a postback, and a page refresh.

After talking (i.e. complaining) to Kyle, he suggested this Stack Overflow solution on implementing a heartbeat pattern, letting the server know when the client was no longer active.

Heartbeat Pattern
In the heartbeat pattern (where you can read more about here), the client will send a signal to the server indicating that it’s still alive every 10 minutes (or whatever time interval you want.)

Look. I made this with MS Paint and, okay?

When a client misses a check-in, the server will know that it is no longer active. At this point, the server can decide to terminate the session (or take another course of action.)


In the main page, I pretty much ripped off the code form the Stack Overflow solution above. There are some minor differences, because I am not using an HTTP handler as suggested. Instead, in the GET request I am (1) requesting an aspx page, (2) sending data to the aspx page, (3) I’m creating an alert with the data that comes back, (4) and I’m leaving empty the last optional parameter.


Instead of using an HTTP handler, I’m using another aspx page. Both this aspx and its code-behind page can be left empty and the session will still be kept alive. But below, I’m returning the data I’ve passed through the GET request and the current date-time.


You can see the working code on my GitHub page. If you have any questions, comments, or suggestions, please let me know!

And thanks to Michael for talking me through the jquery (because I didn’t know any) and letting me avoid HTTP handlers.

Image (in part) via ClassRoomClipArt


Published inOn Coding