JavaScript 防止网页被嵌入 iframe 的两种实现方式

作者:半夏

时间:2026-10-29

浏览:438

本文介绍了两种使用 JavaScript 防止网页被嵌入 iframe 的方法。第一种通过自执行函数保护 window 对象,判断当前窗口与顶层窗口地址是否一致,不一致则强制跳转;第二种采用简洁的一行代码实现相同逻辑,利用短路运算符在顶层位置不等时执行赋值操作,有效避免网站被恶意嵌套。

文章目录

JavaScript 防止网页被嵌入 iframe 的方法

本文介绍了一种利用 JavaScript 防止网页被嵌入 iframe 的技术方案,供读者参考。

方法一:自执行函数保护 window 对象

第一种实现方案如下:


<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>

希望上述内容对您的 JavaScript 编程有所帮助。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章