一、基础嵌套方法
直接在 HTML 中使用 <iframe>
标签指定 src
属性:
-
<iframe src="https://目标网址.com" width="800" height="600"></iframe>
限制:若目标网站设置了 X-Frame-Options
响应头(如 DENY
或 SAMEORIGIN
),嵌套将失败。
二、解决嵌套限制的方案
1.移除响应头限制(后端代理)
通过 Nginx 代理目标网址,隐藏原站点的 X-Frame-Options
或 CSP
策略:
location / {proxy_hide_header X-Frame-Options; # 移除 X-Frame-Options 限制proxy_hide_header Content-Security-Policy; # 移除 CSP 限制proxy_pass https://目标网址.com; # 代理目标网址
}
随后将 iframe 的 src
指向代理地址
2.修改安全策略(后端配置)
在后端代码中主动设置允许嵌套:
- Django 示例:
# settings.py X_FRAME_OPTIONS = 'ALLOW-FROM http://你的域名.com' # 指定允许嵌套的域名
- 通用方案:
在 HTTP 响应头中添加:X-Frame-Options: ALLOW-FROM http://你的域名.com Content-Security-Policy: frame-ancestors 'self' http://你的域名.com
三、跨域通信方法
若需与嵌套页面交互,使用 postMessage
API:
- 父页面发送消息:
// 获取 iframe 的 window 对象 const iframeWindow = document.getElementById('myIframe').contentWindow; // 发送数据(目标需同意跨域) iframeWindow.postMessage('数据内容', 'https://目标网址.com');
嵌套页面接收消息:
window.addEventListener('message', (event) => {if (event.origin !== 'https://父页面域名.com') return; // 验证来源console.log('收到数据:', event.data); });