如何在没有eval的情况下检测异步功能支持? [英] How to detect async function support without eval?
问题描述
这是一种检测当前引擎是否支持异步功能的方法:
Here's one way to detect if the current engine supports async functions:
const supportsAsyncFunctions = (() => {
try {
new Function('async () => {}')();
} catch (error) {
return false;
}
return true;
})();
但是有没有不用eval
或Function
的方法吗?
But is there a way to do it without using eval
or Function
?
推荐答案
建议的eval
方法将为CSP错误提供错误否定,因为它们没有得到处理.如果这是一个问题,则可以按照
Suggested eval
way will give false negatives for CSP errors because they are not handled. If this is a problem, CSP errors can be handled as shown in this answer.
可以这样做,但是解决方案一点也不漂亮,涉及到外部脚本.该脚本可以设置标志,也可以设置全局错误处理程序以在加载脚本时监视语法错误.
It is possible to do that, but the solution is not pretty at all and involves external script. The script can set a flag, or global error handler can be set up to watch for syntax errors when the script is loaded.
如果脚本导致语法错误,则仍然认为该脚本已加载,因此网络问题不会导致误报:
If the script results in syntax error, it is still considered loaded, so network problems cannot cause false positives:
async-detection.js
window.isAsyncAvailable = true;
async () => {};
main.js
new Promise(function (resolve, reject) {
var script = document.createElement('script');
document.body.appendChild(script);
script.onload = resolve.bind(null, true);
script.onerror = reject;
script.async = true;
script.src = 'async-detection.js';
})
.then(function () {
console.log(window.isAsyncAvailable);
})
.catch(/* generic script loading error */);
此方法可用于检测网站上使用的语法功能,这些语法功能不能被try..catch
填充或正常捕获.可靠地触发您的浏览器已过时导航屏幕特别有用.
This method can be used to detect syntactic features used on the website that cannot be polyfilled or normally caught with try..catch
. It is particularly useful to reliably trigger Your browser is outdated nag screen.
这篇关于如何在没有eval的情况下检测异步功能支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!