JavaScript 防止网页被嵌入 iframe 的两种实现方式
作者:半夏时间:2026-10-29 12:11:18浏览:440
本文介绍了两种使用 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 编程有所帮助。
作者最新文章
JavaScript闭包与类(Class)的区别及适用场景对比
2026-11-05 15:48:57
JavaScript入门要学ES6吗?let与箭头函数等新特性解析
2026-11-05 14:49:16
JavaScript 8种数据类型详解:基本类型与引用类型的区别
2026-11-05 14:25:15
怎么在JavaScript中使用async/await优化Ajax异步流程
2026-11-05 13:56:15
JavaScript replace回调函数实现动态正则替换逻辑
2026-11-05 13:52:13
