我有一些打开链接的代码。该链接是可配置的,因此我正在做一些基本的错误处理。具体来说,我用 try/catch 封装了 window.open()
调用,因为如果 URL 无效,内置 API 将抛出异常。问题是,在 Safari 中,捕捉不会被击中。
我尝试查看 Safari API,但找不到任何有用的信息。
下面的示例在 IE 和 Chrome 中运行良好,但在 Safari 中运行不正常。
$(function() {
$('button').on("click", function() {
try {
var begin = "http://<";
var opentag = "script>";
var stuff = "function(){alert('unsafe');}";
var all = begin + opentag + stuff;
window.open(all);
} catch (e) {
alert("errr");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Click ME
</button>
最佳答案
我认为 Barmar 的评论是正确的。一种解决方法是获取 window.open() 的返回值并检查它是否返回任何内容。如果没有,那么它可能没有打开 window 。在此处阅读 window.open() 文档: https://developer.mozilla.org/en-US/docs/Web/API/Window/open
$(function() {
$('button').on("click", function() {
var x = null;
try {
var begin = "http://<";
var opentag = "script>";
var stuff = "function(){alert('unsafe');}";
var all = begin + opentag + stuff;
x = window.open(all);
} catch (e) {
alert("errr");
} finally {
if (!x) {
alert("errrrrrrrrr!");
}
}
});
});
关于javascript - 无法在 Safari 中捕获 window.open() 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46286766/