gpt4 book ai didi

javascript - 如何在没有评估的情况下检测异步功能支持?

转载 作者:可可西里 更新时间:2023-11-01 01:33:59 27 4
gpt4 key购买 nike

这是检测当前引擎是否支持异步函数的一种方法:

const supportsAsyncFunctions = (() => {
try {
new Function('async () => {}')();
} catch (error) {
return false;
}

return true;
})();

但是有没有办法不使用 evalFunction 来做到这一点?

最佳答案

建议的 eval 方法将对 CSP 错误给出漏报,因为它们未被处理。如果这是一个问题,可以按 this answer 中所示处理 CSP 错误。 .

可以这样做,但解决方案一点也不漂亮,并且涉及外部脚本。脚本可以设置标志,或者可以设置全局错误处理程序以在加载脚本时监视语法错误。

如果脚本导致语法错误,仍然认为它已加载,因此网络问题不会导致误报:

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 */);

此方法可用于检测网站上使用的不能被 polyfill 或通常用 try..catch 捕获的句法特征。可靠地触发您的浏览器已过时 导航屏幕特别有用。

关于javascript - 如何在没有评估的情况下检测异步功能支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43502448/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com