我是新来的,所以我没有足够的声誉来评论答案,如果我做错了,我深表歉意,但遗憾的是,公认的解决方案将无法完成您正在寻找的内容。
一旦 DOM 准备好,我就可以通过运行上面 JSFiddle 中的脚本来证明我的意思(不会有警报,但控制台中仍然会出现错误)。以下是有关该小提琴当前发生的情况的更多详细信息:
// running with the No wrap - in <head> option
var frame = document.querySelector('iframe'); // null, the iframe isn't there yet
try {
frame.src="http://wedesignthemes.com/themes/redirect.php?theme=wedding";
} catch(e) {
// TypeError here, no hints about the iframe :(
alert('Error!');
}
被捕获的异常与 iframe 无关,它实际上是尝试在 null 值上设置 src 属性的类型错误。
您真正想要做的是捕获 iframe 的错误inside(当沙盒脚本尝试访问window.top 时),但由于Same-origin policy,这是不可能的。顺便说一句,设置 "allow-same-origin" 沙盒标志仅在 iframe 内容从与顶级文档相同的 origin 提供时才有任何效果。例如。只要 iframe 的 src 或 location 更改为不同的 origin、there's no way to touch anything inside。
有多种方法可以跨越iframe 边界进行通信,例如使用window.postMessage 或使用iframe 的location.hash 的更老和更老套的方式,但我假设您不能影响进入的页面的来源你的 iframe。 (一个优秀的开发人员当然会乐于接受建议,并认为这样的功能可能很有用。)
在不违反任何浏览器安全策略的情况下,我能够捕获此错误的唯一方法是设置 allow-top-navigation 沙盒标志,然后使用顶级文档中的 window.onbeforeunload 处理程序来捕获来自孩子的导航尝试iframe。我永远不会推荐这个,因为用户体验糟糕。如果不提示用户是否要离开页面,就无法阻止导航。下面的概念证明:
<iframe id="myframe" sandbox="allow-scripts allow-top-navigation"></iframe>
<script>
var url = "http://wedesignthemes.com/themes/redirect.php?theme=wedding",
frame = document.getElementById("myframe"),
listener;
listener = window.addEventListener("beforeunload", function(e) {
e.preventDefault();
e.stopImmediatePropagation();
// The iframe tried to bust out!
window.removeEventListener("beforeunload", listener);
return "This is unavoidable, you cannot shortcut a " +
"navigation attempt without prompting the user";
});
frame.src = url;
</script>
很遗憾,如果没有您的第 3 方内容开发人员的帮助,我无法在当前的浏览器实现中找到任何方法来很好地做到这一点。我在 HTML5 规范中读到了一些有趣的东西,它们可能允许我们在未来做这样的事情(不幸的是,我可以在这里插入的链接数量已经达到极限),所以我会密切关注事情的进展。