Framebuster 防点击劫持代码为啥在某些浏览器里失效了?

爱欢 Dev 阅读 10

我最近在项目里加了个防点击劫持的 Framebuster 脚本,但测试时发现 Chrome 和 Firefox 表现不一致——有时候页面还是能被嵌入 iframe。我明明写了判断 top 是否等于 self 的逻辑,难道现在这种方法已经过时了?

我试过把脚本放在 <head> 里、也试过放 body 开头,但都没彻底解决问题。是不是现代浏览器有啥新策略?或者我的写法有漏洞?

if (top !== self) {
  top.location = self.location;
}
我来解答 赞 2 收藏
二维码
手机扫码查看
2 条解答
开发者艺嘉
sandbox 属性会静默阻止 top.location 修改,JS 方案已经不靠谱了。直接上 HTTP 响应头,一劳永逸:

X-Frame-Options: DENY
Content-Security-Policy: frame-ancestors 'none'


后端或者 Nginx 配一下就行,别折腾 JS 判断了。
点赞 1
2026-03-02 16:08
司马爱丹
懒人方案:别用 top.location = self.location,这玩意儿早被浏览器封了。
用 CSP 的 frame-ancestors 头配合前端兜底逻辑:

if (window.top !== window.self) {
document.documentElement.innerHTML = '';
window.stop();
}


但重点是后端加响应头:Content-Security-Policy: frame-ancestors 'self',这才是现代标准解法。
点赞 2
2026-02-24 18:23