Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most reliable approach to detecting browser feature support?

Tags:

javascript

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?

like image 506
Andrey Shchekin Avatar asked Jun 15 '13 00:06

Andrey Shchekin


1 Answers

So essentially there are two choices.

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.

like image 89
Andrey Shchekin Avatar answered Oct 02 '22 15:10

Andrey Shchekin