Reliability of onbeforeunload
Asked Answered
C

1

16

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?
Contrivance answered 30/5, 2013 at 15:39 Comment(3)
1-Yes, 2-No, 3-No, it must return a string synchronously or else the unload continues, 4-No, it is the only way to possibly interrupt the page being unloaded.Culberson
thank you kolink! might you enlighten me, why you didn't post this as an answer which I could accept? (I'm kind of new to this whole stackoverflow thing)Gink
I was fully expecting this question to be closed as unhelpful. Apparently that was just me! I'll go ahead and make it an answer.Culberson
C
14
  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.

Culberson answered 30/5, 2013 at 20:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.