Nick Josevski
Nick Josevski

Reputation: 4216

Using JavaScript or jQuery how to check if event exists on the window?

Setup

I've attached an event to the 'window' object, and I would like to check that it's there via code.

window.addEventListener('beforeunload', function(e){ /*...*/ }, false)

Attempts

I've tried the simple, and jQuery, without luck. I have more attempts up on jsFiddle.

window.beforeunload //is undefined as is window.onbeforeunload

$(window).data('events') //not working either

Is this possible?

There are similar questions (here and here) about the DOM, and other elements, but none of the approaches in those that I have tried have worked.

Upvotes: 5

Views: 6993

Answers (1)

user1106925
user1106925

Reputation:

You can use the in operator...

'onbeforeunload' in window;  // true (if supported)

If supported, the property will exist, though the value will be null.

Upvotes: 10

Related Questions