Unfortunately kangax's answer doesn't work for Safari on iOS. In my testing beforeunload
was supported in every browser I tried exactly except Safari on IOS :-(
Instead I suggest a different approach:
The idea is simple. On the very first page visit, we don't actually know yet if
beforeunload
is supported. But on that very first page, we set up both an
unload
and a beforeunload
handler. If the beforeunload
handler fires, we set a
flag saying that beforeunload
is supported (actually beforeunloadSupported =
"yes"
). When the unload
handler fires, if the flag hasn't been set, we set the
flag that beforeunload
is not supported.
In the following we'll use localStorage
( supported in all the browsers I care
about - see http://caniuse.com/namevalue-storage ) to get/set the flag. We
could just as well have used a cookie, but I chose localStorage
because there
is no reason to send this information to the web server at every request. We
just need a flag that survives page reloads. Once we've detected it once, it'll
stay detected forever.
With this, you can now call isBeforeunloadSupported()
and it will tell you.
(function($) {
var field = 'beforeunloadSupported';
if (window.localStorage &&
window.localStorage.getItem &&
window.localStorage.setItem &&
! window.localStorage.getItem(field)) {
$(window).on('beforeunload', function () {
window.localStorage.setItem(field, 'yes');
});
$(window).on('unload', function () {
// If unload fires, and beforeunload hasn't set the field,
// then beforeunload didn't fire and is therefore not
// supported (cough * iPad * cough)
if (! window.localStorage.getItem(field)) {
window.localStorage.setItem(field, 'no');
}
});
}
window.isBeforeunloadSupported = function () {
if (window.localStorage &&
window.localStorage.getItem &&
window.localStorage.getItem(field) &&
window.localStorage.getItem(field) == "yes" ) {
return true;
} else {
return false;
}
}
})(jQuery);
Here is a full jsfiddle with example usage.
Note that it will only have been detected on the second or any subsequent page loads on your site. If it is important to you to have it working on the very first page too, you could load an iframe
on that page with a src
attribute pointing to a page on the same domain with the detection here, make sure it has loaded and then remove it. That should ensure that the detection has been done so isBeforeunloadSupported()
works even on the first page. But I didn't need that so I didn't put that in my demo.