12

This has / may have been asked before, but, as far as I remember, the question was not satisfactory answered at that time ^^

How can I register a window or tab closing event with Javascript? I have tried body.onclose and body.onunload, and dozens others whose names I made up myself and thought they might possibly exist, but none of it worked, or, if it did, it only fired after the window or tab has been closed.

Question: Is there any way to register such an event before the window or tab has been closed? It needn't even be compatible with all browsers, as long as it works with Firefox.

tshepang
  • 12,111
  • 21
  • 91
  • 136
arik
  • 28,170
  • 36
  • 100
  • 156

4 Answers4

20

window.onbeforeunload= …;.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
8
window.onbeforeunload = function (e) {
  var e = e || window.event;

  // For IE and Firefox
  if (e) {
    e.returnValue = 'Any string';
  }

  // For Safari
  return 'Any string';
};
Benjamin
  • 11,560
  • 13
  • 70
  • 119
Imtiyaz
  • 81
  • 1
  • 1
1

WE don't have Onclose but we have OnbeforeUnload. Even I am looking for same event but no luck.

Rinkesh
  • 11
  • 1
0

Unload and beforeUnload have negative effects on the "page cache" (also known as the "back forward cache"). This is a special cache that preserves some extra state when you navigate away from the page, so that it can be seamlessly resotred when you navigate 'back' (or unclose a tab). If you've ever wondered why some form fields keep their contents when you click back and some don't - this is often part of the reason.

You should probably take a look at the "pageshow" and "pagehide" events in Firefox and WebKit. IE doesn't have a page cache equivalent, so in that environment you should be fine to use before/unload. Despite Opera's early concerns, pageshow and pagehide made it into the HTML5 Spec

pete otaqui
  • 1,432
  • 14
  • 11