18

Can I rely on the window unload event to be triggered when a user closes a tab/window/browser?

Edit:

Found a list of what triggers the unload event in IE. http://msdn.microsoft.com/en-us/library/ms536973%28VS.85%29.aspx

I would like to know in which edge cases the unload event won't be triggered.

tshepang
  • 12,111
  • 21
  • 91
  • 136
bhseo
  • 276
  • 1
  • 2
  • 7
  • youd have to give more use case - what is it that you want to achieve with the unload? There might be other ways to implement that feature other than unload events. – Chii Oct 20 '09 at 13:34

2 Answers2

10

You will likely want to use the "onbeforeunload" event too, it provides more control than the "onunload" event.

That said, be aware that: Opera doesn’t fire the unload event when the browser refreshes the page, or uses the back/forward buttons to browse off of the page. What’s worse, Opera never fires the onbeforeunload event. Thus if you are supporting Opera - be aware of these issues.

scunliffe
  • 62,582
  • 25
  • 126
  • 161
5

Not in all circumstances no. The browser could crash etc. keeping the event from firing. The user could also use add-ons like Grease Monkey to prevent the event from firing also.

kemiller2002
  • 113,795
  • 27
  • 197
  • 251
  • 2
    That's why I said "when a user closes". Browser crashes, power outages,etc. are a different case. – bhseo Oct 20 '09 at 13:39
  • Well a user can still close the browser by using task kill etc. – kemiller2002 Oct 20 '09 at 13:46
  • 1
    If you are relying on it to fire to clean something up, you can't. – kemiller2002 Oct 20 '09 at 13:47
  • Fair enough. I was also just thinking about the user shutting down the OS, or going to stand-by or hibernating. – bhseo Oct 20 '09 at 13:49
  • As far as I know, hibernation DOES NOT propagates WM_CLOSE message across the system (because it is not closing anything, in fact), so you're surely CAN'T react in `onunload` or `onbeforeunload` on sitation like user hibernating its system! – trejder Jul 17 '12 at 14:15