会,空 sandbox 属性触发默认拒绝策略,所有主动行为(含脚本执行、事件绑定、console.log 等)被硬性拦截;仅 allow-scripts 可执行外链脚本,但禁内联脚本、localStorage 访问及动态 script 插入。

会,而且不止禁用脚本——所有主动行为全被静默拦截,连 alert(1) 都不会弹,控制台也不报错。
为什么 sandbox 或 sandbox="" 后 JS 一概不执行
这不是脚本加载失败或语法错误,是浏览器在解析 HTML 阶段就跳过整个脚本引擎:
- <script>alert(1)</script> 被直接忽略
- onclick="fetch()" 绑定无效,点击无响应
- javascript:void(0) 链接点击后空白
- eval()、setTimeout("alert(1)")、document.write() 全部失效
- 连 console.log("test") 都不会输出,Network 面板里也看不到脚本请求
根本原因是:空 sandbox 属性触发“默认拒绝”策略,iframe 被强制赋予 null origin,所有主动行为能力被硬性切断。
sandbox="allow-scripts" 能解什么、不能解什么
这是最常加也最容易误解的权限项:
- ✅ 允许外链脚本执行:<script src="https://trusted.example/widget.js"></script>(需服务端返回 Access-Control-Allow-Origin)
- ❌ 不允许内联脚本:<script>alert(1)</script>、onclick="alert(1)"、javascript:void(0) 仍被屏蔽
- ❌ 不恢复 localStorage、document.cookie 访问权,仍报 SecurityError
- ❌ 不允许动态插入新 <script> 标签(即脚本里再 document.createElement("script") 仍被拦截)
- ❌ window.parent、window.top 仍是 null,无法访问父页面 DOM
动态设置 iframe.sandbox 为什么无效
必须在 iframe 插入 DOM 前就写死属性值,否则浏览器已按“空 sandbox”完成初始化:
- ❌ const iframe = document.createElement("iframe"); iframe.sandbox = "allow-scripts"; document.body.appendChild(iframe); → 不生效
- ✅ 正确写法:const iframe = document.createElement("iframe"); iframe.setAttribute("sandbox", "allow-scripts"); document.body.appendChild(iframe);
- ✅ 或直接写 HTML:<iframe src="widget.html" sandbox="allow-scripts"></iframe>
- ⚠️ 注意:sandbox="allow-scripts "(末尾空格)、sandbox="allow-scripts( )" 等非法格式会被当空值处理,等同于全锁死
容易被忽略的边界情况
哪怕你只想要 JS 运行,也要注意这些细节:
- src 是 data: 或 javascript: 协议时,大多数浏览器直接拒绝加载,allow-scripts 也救不了
- allow-same-origin 和 allow-scripts 同时存在且 src 真为同源时,iframe 会获得读写 localStorage 和父页面 DOM 的能力——但一旦父页有 XSS 漏洞,沙箱反而成攻击跳板
- document.querySelector("iframe").sandbox 返回空 DOMTokenList [] 就说明当前是全锁死状态,别猜,直接查这个值



















