【发布时间】:2011-04-18 22:36:10
【问题描述】:
这个问题之前asked and answered是正确的,但似乎没有发布解决方案。
如果一个网站有 iframe,并且想要防止它们被包含在来自不同域的框架中,那么简单的框架破坏将没有用:
<script>if (top != self) top.location = location</script>
但是,由于对其他域的跨框架脚本会产生异常,因此在 iframe 中似乎可以正常运行:
<script>
try {
if (window.document.domain != top.document.domain) { // throws exception
throw "You naughty puppy!"; // Should not ever get here, right?
}
}
catch () {
top.location = "/error/naughtypuppy";
}
</script>
上面的 if 本身应该足以防止 iframe 的跨域框架。它应该只返回false 或抛出异常,那么脚本是否可以在浏览器中访问throw 语句?
这是否足以防止仅来自其他域的框架?
<script>
try {
var bogus = top.document.domain;
}
catch () {
top.location = "/error/naughtypuppy";
}
</script>
编辑:这里暗示了一个类似的解决方案,但不会依赖父框架来包含框架破坏代码。 Detect when iframe is cross-domain, then bust out of it 。基本上与“尝试访问其他框架并在发生异常时破坏”的解决方案相同。
【问题讨论】:
-
我之前评论中的答案并不完全有效。恶意代码在加载框架时不会包含
onload="checkForCross()",因此最好在 child.html 页面而不是父框架中包含 checkForCross 函数。 -
我想我会认为我的解决方案是正确的。
标签: javascript iframe same-origin-policy