if (top.location!= self.location) {
top.location = self.location.href;
}
这通常会起作用,但在 window
被覆盖的情况下,可能会失败。以下是来自 Nathan Smith 的几个巧妙的替代方案 。
<script>
// Break out of an iframe, if someone shoves your site
// into one of those silly top-bar URL shortener things.
//
// Passing `this` and re-aliasing as `window` ensures
// that the window object hasn't been overwritten.
//
// Example:
// var window = 'haha, punked!';
//
// Note: Probably unnecessary, but just for kicks.
(function(window) {
if (window.location !== window.top.location) {
window.top.location = window.location;
}
})(this);
</script>
<script>
// A more cryptic one-liner, to awe & impress.
//
// No need to protect `window` since `this` is
// immutable, and at the topmost level means
// `window` anyways. Here, we compare locations
// on the left side of the "&&" and execute the
// code in parenthesis if that condition is
// true (top location isn't iframe location).
//
// Otherwise, nothing happens. It's basically an
// if statement without wrapping curly brackets.
//
// Weird, I know. But pretty cool, right? :)
this.top.location !== this.location && (this.top.location = this.location);
</script>
有没有办法从父级阻止它?
也许可以尝试分派父级 window.top,因为它只供 HTMLIFrameElement 使用。
请提供使用 iframe 的博客示例。
无法在 word press 上使用它。
有一个 WordPress 插件 > http://wordpress.org/plugins/wp-framebreaker/
如果我使用 Google Analytics 进行跟踪,这会导致注册两次访问吗?
如果是,有没有其他方法可以跳出 iframe,但不注册两次访问?
这无法保证有效 - 设置 window.top.location 可以绕过 (http://en.wikipedia.org/wiki/Framekiller#Framekiller_killers)。 相反,您应该使用维基百科部分中直接描述的选项 - 仅在检测到您不在 iframe 中时才设置可见。
您的第一个代码段不应该吗?
当我尝试不使用“href”部分时,它会导致重定向,而不仅仅是跳出 iframe。
抱歉,请忽略我之前的评论。看起来添加“.href”也会进行重新加载。不确定为什么当我第一次尝试不使用重新加载时,它似乎可以工作!我应该在发布之前的帖子之前做更多测试!真可惜它必须重新加载页面。不过,感谢您的信息。
@Miro,您实际上是不正确的。该研究存在缺陷。请参见我在维基百科上关于此方面的编辑:https://en.wikipedia.org/wiki/Framekiller
这里提出的解决方案是消除框架的最佳选择。
HTML5 新特性
iframe sandbox=”allow-same-origin”
允许 iframe 内容被视为来自同一来源。
这对我来说很有效,让我们看看能持续多久。
我知道这篇文章很旧,但我尝试了它,效果很好。问题是,如果我使用“Visual Composer”(WordPress 的一个可视化构建器),它会将我重定向到该帖子,我无法使用 Visual Composer..
如果域相同,有没有办法阻止它?
谢谢!
不幸的是,这在 WP Customizer 中不起作用,也会将其删除/重定向。
哇,太棒了!
我一直努力让我的网站看起来漂亮,但是重定向到登录页面是一个问题,因为登录页面扭曲了所有内容。这行代码太棒了。