我有一个 (ASP.Net) 应用程序,它具有以下客户端 Javascript,以便于复制到剪贴板:
var ua = window.navigator.userAgent;
var is_ie = /MSIE|Trident/.test(ua);
if (is_ie) {
var input = document.getElementById("inputcopy"); // select it
input.value = text;
input.select();
document.execCommand("copy");
this.focus();
}
else {
navigator.clipboard.writeText(text).then(() => {
writeLog('Copy successful');
if (showalert == true) alert('Copied to clipboard');
}).catch(() => {
writeLog('Copy failed');
if (showalert == true) alert('Copy to clipboard failed');
});
}
我们需要与所有“现代”浏览器兼容 - Chrome、Firefox,还有 IE11(别开枪)。前两个还好,但后者......
由于 IE 不支持 navigator.clipboard
,我在其中添加了 if (is_ie)
,效果很好。然而,IE 不知道非 IE 部分中的 Promise
,并且在
navigator.clipboard.writeText(text).then(() => {
即使它永远不会真正运行它。
我怎样才能告诉 IE 忽略那段代码,或者解决这个问题?我研究过根据浏览器有条件地加载单独的 JS 文件,但这看起来不太有趣。有更好的选择吗?
最佳答案
根据OP的建议添加我的评论作为答案。
您可以尝试 eval() 来解决此问题。 eval()
的作用是将字符串解析为可执行代码。这实际上会让 IE 忽略这段代码,因为它无论如何也不会执行。
是的,我们通常不使用eval()
,但像这样的罕见场景是使用它的完美理由。
这里有一些关于 eval 的资源:Why is using the JavaScript eval function a bad idea?
或者如果可能的话,只需使用 Promise Polyfill。
正如 @Quentin 所解释的,仅使用函数表达式就可以轻松解决此问题,而无需使用 eval()
。
关于javascript - 在 IE11 中忽略 "syntax errors",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55647350/