检测浏览器功能支持的最可靠方法是什么? [英] What is the most reliable approach to detecting browser feature support?

查看:71
本文介绍了检测浏览器功能支持的最可靠方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想检测对通知的支持( http://notifications.spec.whatwg.org/ )在JavaScript库中。

Let's say I want to detect support for notifications (http://notifications.spec.whatwg.org/) in a JavaScript library.

我可以使用 window.Notification!== undefined 。但是,如果库(或其他库)的用户也有某种全局通知对象被定义为完全不同的目的呢?

I can use window.Notification !== undefined. But what if the users of the library (or another library) also have some kind of global Notification object defined for completely different purpose?

另一方面,如果另一个库是polyfill怎么办?然后他们的通知对象是可以接受的。除了测试全局对象之外,我应该测试所有方法吗?

On the other hand, what if the other library is a polyfill? Then their Notification object is acceptable. Should I test for all methods in addition to testing for the global object?

更新:

我注意到一个有趣的事情在一个通知polyfill

ret[toString] = function() {
    return 'function Notification() { [native code] }';
};

依靠这样的东西检测它是否是原生/填充对象有多可靠?

How reliable is relying on something like that to detect whether it is a native/polyfill object?

推荐答案

所以基本上有两种选择。

So essentially there are two choices.

首先是尝试和依赖'函数Notification(){[native code]}' toString value,因为它是由某些人设置的至少是polyfills。不幸的是,这不可靠,因为我没有找到关于它是否是polyfill作者中常见方法的信息,以及它是否是浏览器中可靠的返回值。

First is to try and rely on 'function Notification() { [native code] }' toString value, as it is being set by some polyfills at least. Unfortunately, this not reliable, as I found no information on whether it is a common approach within polyfill authors and whether it is a reliable return value in browsers.

另一种选择,正如评论中所建议的那样,是忽略潜在的冲突,只是前进只是为了存在而进行测试。这就是我现在所用的。

Another option, as suggested in comments, is to ignore potential conflicts and just go forward just testing for existence. That's what I went with for now.

这篇关于检测浏览器功能支持的最可靠方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆