Question

How reliable is the event window.onbeforeunload?

  1. Does it fire in all major browsers?
  2. Does it fire if the client browser crashes?
  3. Is it able to delay the close event in case it might need "a little longer" or will it get cut off?
  4. Are there any alternatives?
Was it helpful?

Solution

  1. Does it fire in all major browsers?
    Yes, onbeforeunload works in every browser I have ever tried it on.

  2. Does it fire if the client browser crashes?
    No, if a browser crashes then it dies, there is no way around that fact.

  3. Is it able to delay the close event in case it might need "a little longer" or will it get cut off?
    I said "no" in my comment, but it does depend somewhat. For instance, if you have a really long loop, it will fully execute before the page closes. However, you cannot use AJAX or any other asynchronous function like setTimeout within the handler. It MUST return a string in a synchronous manner in order to block unloading.

  4. Are there any alternatives?
    Again, I said "no" in my comment, but I can elaborate further. If you attach an event handler to your page to detect a click on a link, you can then manually call the onbeforeunload handler to get the string response, and use that to show a custom confirmation box, cancelling the click event as you do so. Note that this will not affect reloading, Back, Forward or Close buttons, only clicking on a link to a new page. You should also take care to not affect links to anchors on the same page, or javascript:void(null);-type links. This will allow you to make AJAX requests too, and if the user confirms wanting to leave the page you can do some things before loading the new page.

    Long story short, there are alternatives in some cases, but it all stems from the onbeforeunload event and can be quite complex.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top