onbeforeunload support detection

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) {
else {

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?


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.

Different approach, get the typeof

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

alert("hello functionality!");
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;


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

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


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

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(){
    return 'beforeunload event';

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

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

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' );


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.