View Full Version : emulating onbeforeunload

09-23-2005, 08:02 PM
Hey guys

Does anyone know how to emulate an onbeforeunload event in browsers using the Gecko DOM - essentially I want to allow an AJAX request to be called without being cancelled when the page unloads.

This is for an intranet application - a CMS in fact. There's a legitimate reason for doing this - it's to do with locking html pages to prevent them being edited by more than one user - the onunload "unlocks" the page. I've got it working using an alert onunload to leave enough time for the AJAX request to process, but would like a more discrete way of doing this.

Because of the sensitive nature of the implications (if used wrongly) of a solution to this request, feel free to PM me with replies to this thread. I'm also very aware that there's an extremely high chance that this is simply not possible - I'm a pretty experienced developer and cannot think of a way to do this.

Many thanks


Canuck WebGeek
09-23-2005, 08:36 PM
no need to emulate it. It's already there.

Try it:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

function onBeforeUnloadEvent() {
return 'hello';


<body onbeforeunload="return onBeforeUnloadEvent();">


09-23-2005, 09:30 PM
Nice one, not quite sure how i missed that :rolleyes:

09-24-2005, 12:51 AM
Relying on "unload" event in application like this will result in "permanently" locked pages that you would have to manually go into database and unlock. There is a number of ways the browser can close, such as computer crash, power failure, connection failure, that would cause your application logic failure.
Since you are already using XMLHTTP calls to server, a more robust way would be to "ping" the server every so often (say, 30 sec should be no problem as far as extra resources go) to indicate that the page is in use.

09-24-2005, 01:01 PM
Cheers for the response mate, in fact I set use IIS/ASP Application objects and session events and match valid session id's, so if the session ends (for whatever reason) the CMS handles this. There's no database usage for locking pages.

Cheers for the response, still amazed that I missed onunload in Gecko browsers!!