【问题标题】:Is using 'eventhandler' in window a safe method of determining if window supports a given event handler?在窗口中使用“事件处理程序”是确定窗口是否支持给定事件处理程序的安全方法吗?
【发布时间】:2012-05-11 11:47:32
【问题描述】:

所有功劳归于:

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

对于这种方法,但我们想知道是否执行以下操作:

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

确定窗口对象是否支持 onhashchange 事件处理程序是一种安全的方法吗?

谢谢。

【问题讨论】:

标签: javascript events window handler detect


【解决方案1】:

不,这通常不是一个安全的测试,尽管对于这个特定的事件来说可能没问题,因为它相对较新。无法保证主机对象(例如 window)将如何响应 in 运算符,并且某些浏览器(包括旧版本的 Firefox)不会为事件处理程序属性返回 true。以下文章有详细说明:

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

似乎Firefox added support for detecting event support using the in operator in version 9onhashchangeadded in 3.6,所以除非onhashchange 有特殊行为,否则您的测试将在Firefox 3.6 - 8.0 中给出假阴性。

更新

我现在在 Firefox 3.6 中进行了测试,似乎 onhashchange 是一个特殊情况,因为您的测试有效:'onhashchange' in window 返回 true,而 'onload' in window 则没有。看起来您的测试可能没问题,但我仍然建议您仔细测试所有目标浏览器。

【讨论】:

  • 我们最终使用了文章中提到的方法。适用于各种浏览器。
【解决方案2】:

是的。它检查对象window 中是否存在键'onhashchange' 并返回布尔值。没有不安全的用法。

【讨论】:

    【解决方案3】:

    我会这样做:

    if (window.onhashchange) ...
    

    【讨论】:

    • 那更糟。这个想法是检查浏览器是否支持事件,而不是是否设置了处理程序。
    • 如果其他脚本在你做这个检查之前添加了window.onhashchange=function(){},它将是无效的。
    • 好的,我同意,但它不是比 if('onhashchange' in window) 更好,这不是标准语法 AFAIK...
    • 不,in 运算符是标准语法。 developer.mozilla.org/en/JavaScript/Reference/Operators/in
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    相关资源
    最近更新 更多