9

How can we do JavaScript object detection for pageShow and pageHide handlers?

if( /* pagehide is supported */ ){
   window.addEventListener('pagehide', exitFunction, false);
}
else{
    window.addEventListener('unload', exitFunction, false);
}
epascarello
  • 204,599
  • 20
  • 195
  • 236

1 Answers1

26
if ('onpagehide' in window) {
   window.addEventListener('pagehide', exitFunction, false);
} else {
   window.addEventListener('unload', exitFunction, false);
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Shaz
  • 15,637
  • 3
  • 41
  • 59
  • I just checked. Answer works, but has a flaw. If someone defines onpagehide before this check happens window.onpagehide would be true. I am not sure if there is anyway to avoid that. :( – epascarello Aug 02 '11 at 01:24
  • 8
    @epascarello That's possible with just about anything. You can redefine `getElementById` with `document.getElementById = "nyan cat";` – Shaz Aug 02 '11 at 01:27
  • most browsers will not let you set getElementById. That one is protected. :) – epascarello Aug 02 '11 at 01:41
  • 1
    This answer worked for me in chrome but not firefox although both do support pageshow (I tried with pageshow), firefox always fails the conditional check. – Frug Dec 15 '11 at 16:34
  • 1
    @Shaz The recommended way to check if an event is supported is to use `if ('onpagehide' in window) {`. (See http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ There are a very few exceptions for broken browsers. Expanding on @nilfalse's comment.) – robocat Mar 11 '15 at 21:42
  • The link in the comment above is 404. Here's the updated one: [Detecting event support without browser sniffing](http://perfectionkills.com/detecting-event-support-without-browser-sniffing). – D M Mar 22 '22 at 17:55