0

All credit goes to:

http://benalman.com/news/2010/03/jquery-special-events/#add-and-remove-hashchange

For this method, but we were wondering if doing the following:

if('onhashchange' in window){
    console.log('yep, window supports onhashchange');
}
else{
    console.log('nope, window does not support onhashchange');
}

Is a safe method of determining if the window object supports the onhashchange event handler?

Thanks.

anonymous-one
  • 14,454
  • 18
  • 60
  • 84
  • possible duplicate of [Javascript : onHashchange Test](http://stackoverflow.com/questions/4030390/javascript-onhashchange-test) – Jeremy May 18 '12 at 18:39

3 Answers3

2

No, this is generally not a safe test, although it may be OK for this particular event since it is relatively new. There is no guarantee about how host objects (such as window) will respond to the in operator and some browsers, including old versions Firefox, do not return true for event handler properties. The following article has details:

http://perfectionkills.com/detecting-event-support-without-browser-sniffing/

It seems Firefox added support for detecting event support using the in operator in version 9 while onhashchange was added in 3.6, so unless there was special behaviour for onhashchange, your test will give false negatives in Firefox 3.6 - 8.0.

UPDATE

I've now tested in Firefox 3.6 and it seems onhashchange is a special case because your test works: 'onhashchange' in window returns true, while 'onload' in window, for example, does not. It looks like your test may be OK, although I would still recommend testing all your target browsers carefully.

Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

Yes. It checks if key 'onhashchange' present in object window and return boolean value. There is no unsafe usage.

antyrat
  • 27,479
  • 9
  • 75
  • 76
-1

I would do it like this:

if (window.onhashchange) ...
Bojan Bjelic
  • 3,522
  • 1
  • 17
  • 18
  • That's worse. The idea is to check whether the event is supported by the browser, not whether a handler has been set. – Tim Down May 11 '12 at 12:26
  • If some other script adds `window.onhashchange=function(){}` before you do this check, it will be invalid. – epascarello May 11 '12 at 22:45
  • ok, I agree, but is it not better then `if('onhashchange' in window)` which is not standard syntax AFAIK... – Bojan Bjelic May 12 '12 at 21:11
  • No, the `in` operator is standard syntax. https://developer.mozilla.org/en/JavaScript/Reference/Operators/in – Tim Down May 15 '12 at 08:29