I\'m really enjoying ES6 generators. Is there a way I can detect generator support in browsers? I know generators might not be in a lot of browsers (or possible no browsers at a
Jeremy nicely explained how to test for generators support. You need to use eval:
isGeneratorSupported = function(){
try {
eval("(function*(){})()");
return true;
} catch(err){
return false;
}
}
alert( isGeneratorSupported() );
I will try to explain why your way does not work.
When you check whether some of JS/html5 features are supported and you use something like this:
function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
JS engine parses you code, run it if it properly parsed and then compare the output to what you have expected and only because of this you function can tell that your feature is supported.
When you write the code like function *(){}
JS engine fail on the very first step (parsing your code) and do not even try to execute it. This happens because *
is not a new function, it is a new language construct and older versions of JS engine will just throw a syntaxError
. The same way if you will write function f(x, ...y) {}
, function f(x, y=1){}
or even just ]
. They all are invalid constructs in current JS (but 2 of them are valid in ES6, and who knows maybe ]
will be valid in some ES10.)
The way to bypass it is ask your engine to somehow try to execute it. And by putting your code inside eval()
you can do this.