score:0

on behalf of @denys séguert :

The short answer is that you can't.

The onbeforeunload event was initially introduced by Microsoft to allow a standard confirmation dialog. It is now supported in the original form by most browsers and in most case a short, non interactive, function is allowed to execute (for example you may log your state in the localStorage). But, as described in the cross-browser jQuery API, this is unreliable :

The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers, and contrasted with the proprietary beforeunload event.

As there are many potential security problems related to the execution of a task when the user asked to end the page (and thus the script), this will probably be unreliable until (and if) a serious normalization effort is done to precise what exactly can be done in a onbeforeunload callback.

For the predictable future, it's recommended to not depend on onbeforeunload but to use other schemes, for example constant background saving or a big "save" button.


Related Query

More Query from same tag