21

I'd like to check if the current browser supports the onbeforeunload event. The common javascript way to do this does not seem to work:

if (window.onbeforeunload) {
    alert('yes');
}
else {
    alert('no');
}

Actually, it only checks whether some handler has been attached to the event. Is there a way to detect if onbeforeunload is supported without detecting the particular browser name?

jansokoly
  • 1,994
  • 2
  • 18
  • 25

10 Answers10

28

I wrote about a more-or-less reliable inference for detecting event support in modern browsers some time ago. You can see on a demo page that "beforeunload" is supported in at least Safari 4+, FF3.x+ and IE.

Edit: This technique is now used in jQuery, Prototype.js, Modernizr, and likely other scripts and libraries.

kangax
  • 38,898
  • 13
  • 99
  • 135
  • 1
    Is the site that's linked to above down? Doesn't work for me but I found a [cached version](http://webcache.googleusercontent.com/search?q=cache:http://perfectionkills.com/detecting-event-support-without-browser-sniffing/). – regularmike May 07 '12 at 17:55
  • 1
    Warning: I wrote a comment on [@kangax's page](http://perfectionkills.com/detecting-event-support-without-browser-sniffing/#comment-468226) specifically about `onbeforeunload` being detected as supported on Mobile Safari even though it [actually doesn't work reliably](http://stackoverflow.com/questions/3239834/window-onbeforeunload-not-working-on-the-ipad). – Peter V. Mørch Aug 07 '13 at 10:43
8

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.

Community
  • 1
  • 1
Peter V. Mørch
  • 13,830
  • 8
  • 69
  • 103
7

I realize I'm a bit late on this one, but I am dealing with this now, and I was thinking that something more like the following would be easier and more reliable. This is jQuery specific, but it should work with any system that allows you to bind and unbind events.

$(window).bind('unload', function(){
    alert('unload event');
});

window.onbeforeunload = function(){
    $(window).unbind('unload');
    return 'beforeunload event';
}

This should unbind the unload event if the beforeunload event fires. Otherwise it will simply fire the unload.

Paul McLanahan
  • 103
  • 1
  • 3
3
alert('onbeforeunload' in window);

Alerts 'true' if onbeforeunload is a property of window (even if it is null).

This should do the same thing:

var supportsOnbeforeunload = false;
for (var prop in window) {
    if (prop === 'onbeforeunload') {
    supportsOnbeforeunload = true;
    break;
    }
}
alert(supportsOnbeforeunload);

Lastly:

alert(typeof window.onbeforeunload != 'undefined');

Again, typeof window.onbeforeunload appears to be 'object', even if it currently has the value null, so this works.

Grant Wagner
  • 25,263
  • 7
  • 54
  • 64
  • almost works fine in IE, Opera and Safari, but FF gives me false, which does not seem to be correct – jansokoly Oct 01 '08 at 17:47
  • Sorry, I thought it was working reliably because I didn't realize Firefox supported onbeforeunload. – Grant Wagner Oct 01 '08 at 17:55
  • Firefox doesn’t support that kind of inference, but allows to detect “beforeunload” be setting corresponding attribute on an element. var el = document.createElement('div'); el.setAttribute('onbeforeunload', ''); typeof el.onbeforeunload; // "function" – SavoryBytes Dec 05 '10 at 07:07
  • This didnt work for me in iOS Safari. It will say the beforeunload event is supported even if it is not – ajaybc Jan 11 '17 at 07:57
3

Cruster,

The "beforeunload" is not defined in the DOM-Events specification, this is a IE-specific feature. I think it was created in order to enable execution to be triggered before standard "unload" event. In other then IE browsers you could make use of capture-phase "unload" event listener thus getting code executed before for example an inline body onunload event.

Also, DOM doesn't offer any interfaces to test its support for a specific event, you can only test for support of an events group (MouseEvents, MutationEvents etc.)

Meanwhile you can also refer to DOM-Events specification http://www.w3.org/TR/DOM-Level-3-Events/events.html (unfortunately not supported in IE)

Hope this information helps some

Sergey Ilinsky
  • 31,255
  • 9
  • 54
  • 56
  • 1
    Thanks buddy, but this is just all theory - see other answers to this questions and you'll find almost perfect solutions. So, I really don't care if DOM does offer some interface or not. In reality, there are reliable ways how to check it, that's important. Oh, btw., only Opera lacks the support. – jansokoly Oct 06 '08 at 13:36
0

Different approach, get the typeof

if(typeof window.onbeforeunload == 'function')

{
alert("hello functionality!");
}
curtisk
  • 19,950
  • 4
  • 55
  • 71
0

onbeforeunload is also supported by FF, so testing for browser won't help.

0

Mobile browsers don't tend to not support beforeunload because the browser can go into the background without unloading the page, then be killed by the operating system at any time.

However, all modern non-mobile browsers support it. Therefore, you can just check if the browser is a mobile browser.

To solve the problem I use:

var isMobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone|iPad|iPod/i) || navigator.userAgent.match(/Opera Mini/i) || navigator.userAgent.match(/IEMobile/i);
if (isMobile)
{
    window.addEventListener("visibilitychange", function(e)
    {
        if (document.visibilityState == 'hidden')
        {
            console.log("beforeunload");
            location.reload();
        }
    });
}
else
{
    window.addEventListener("beforeunload", function(e)
    {
        console.log("beforeunload");
    });
}
Dan Bray
  • 7,242
  • 3
  • 52
  • 70
-1

I see that this is a very old thread, but the accepted answer incorrectly detects support for Safari on iOS, which caused me to investigate other strategies:

if ('onbeforeunload' in window && typeof window['onbeforeunload'] === 'function') {
  // onbeforeunload is supported
} else {
  // maybe bind to unload as a last resort
}

The second part of the if-check is necessary for Safari on iOS, which has the property set to null.

Tested in Chrome 37, IE11, Firefox 32 and Safari for iOS 7.1

thetallweeks
  • 6,875
  • 6
  • 25
  • 24
  • `onbeforeunload` is always set to null by default. If you set a `onbeforeunload` function it will always be a function. That doesn't mean it's going to be triggered. I don't what you tested, but that won't work. The only way here is iOS device detection or Peter V. Mørch's method. – hexalys Nov 30 '14 at 08:42
-4

It would probably be better to just find out by hand which browsers support it and then have your conditional more like:

if( $.browser.msie ) {
  alert( 'no' );
}

...etc.

The $.browser.msie is jQuery syntax, most frameworks have similar built-in functions since they use them so much internally. If you aren't using a framework then I'd suggest just taking a look at jQuery's implementation of those functions.

rfunduk
  • 30,053
  • 5
  • 59
  • 54