简体   繁体   中英

Javascript register window/tab closing event before window/tab close

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.

window.onbeforeunload = function (e) {
  var e = e || window.event;

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

  // For Safari
  return 'Any string';
};

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM