Basically, our application keeps a form of session state server-side, and it needs to be notified when the browser window is closed or refreshed. Clearly, the thing to do here is to hook into the window.onUnload event (side note for new Atlas developers: don’t use window.onUnload, use Sys.Application.unload.add([yourUnloadHandler]) instead).
So at first I just went happily along, sending the usual XmlHttpRequest when the page unloaded. However, this of course poses a problem with the asynchronous response from the server: by the time the response comes back, the page has unloaded and the callback function won’t exist anymore. This generates an ugly Javacript “function is not defined” error. In any case, here’s a nice little picture of what happens:
The solution here is to make sure that any AJAX requests that you make onUnload are make synchronously instead of asynchronously (SJAX?). This will ensure that the page doesn’t finish unloading before the server response comes back. Hence, the much happier picture below: