两层沙箱
sandbox 属性约束框内页面能做什么;CSP frame-src 约束你能框入什么。两者并用,被攻陷的组件无法提权,非法 iframe 也无法加载。
<iframe src="https://widget.example/embed"
sandbox="allow-scripts allow-same-origin allow-popups"
loading="lazy"></iframe>
先报告再阻断
先把 CSP 以 report-only 上线并观察报告。报告干净后切换为强制,避免悄悄框入不同来源助手的组件被破坏。
Content-Security-Policy-Report-Only: frame-src https://widget.example; report-uri /csp-report
预期结果
组件渲染并运行自身脚本,top.location 抛异常,指向不同来源的 iframe 被阻断。强制头上线后报告端点零违规。需与父窗口通信时用 postMessage 并双向校验来源。allow-scripts 与 allow-same-origin 组合已是最宽松,不应再放宽。