10

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

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?

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?

Update:
I have noticed an interesting thing in one notifications 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?

4

2 回答 2

1

所以基本上有两种选择。

首先是尝试依赖'function Notification() { [native code] }' toString值,因为它至少是由一些 polyfill 设置的。不幸的是,这并不可靠,因为我没有发现关于它是否是 polyfill 作者中的常用方法以及它是否是浏览器中的可靠返回值的信息。

正如评论中所建议的,另一种选择是忽略潜在的冲突,而只是继续测试是否存在。这就是我现在所做的。

于 2013-06-15T23:32:23.047 回答
0

您始终可以采用 jQuery 方法并重新定义引用预先存在的 window.Notifications 的任何内容,例如:

window._Notification = window.Notification;

Paul Irish 在这段视频中有一段很好地解释了它是如何工作的。

这样,您可以继续实施他们正在使用的任何其他功能,同时仍然包括您的功能。

希望有帮助。:)

于 2013-06-15T04:59:16.177 回答