加了sandbox连alert(1)都不弹,是因为等价于全锁死状态:脚本不解析、内联事件被跳过、控制台静默不报错;必须显式写sandbox="allow-scripts"才能执行外链脚本,但内联script、onclick、eval等仍被静默屏蔽。

为什么加了 sandbox 却连 alert(1) 都不弹
因为 <iframe sandbox></iframe> 等价于 sandbox="",浏览器直接进入“全锁死”状态:脚本不解析、内联事件被跳过、fetch() 请求被丢弃、localStorage.setItem() 静默失败,控制台甚至不报错。这不是 JS 写错了,是权限从源头被硬拦截。
验证方法:在控制台执行 document.querySelector('iframe').sandbox,返回空的 DOMTokenList [] 就说明没开任何权限。
-
sandbox=""、sandbox=" "、sandbox(无值)三者完全等效,全部锁死 - 动态设置
iframe.sandbox = "allow-scripts"无效,属性必须在 DOM 插入前就写死 - 想让脚本能跑,唯一起点是显式写
sandbox="allow-scripts"
allow-scripts 能跑什么、不能跑什么
allow-scripts 只解禁外链脚本加载与执行,不恢复任何内联执行能力——这是最容易踩坑的地方。
- ✅ 可运行:
<script src="https://trusted.example/widget.js"></script>(需服务端返回Access-Control-Allow-Origin) - ❌ 不可运行:
<script>alert(1)</script>(内联 script 标签被静默忽略) - ❌ 不可运行:
<button onclick="fetch('/api')">click</button>(内联事件处理器完全失效) - ❌ 不可运行:
javascript:void(0)、eval()、setTimeout("alert(1)")、document.write() - ⚠️ 注意:
allow-scripts不递归授权——外链脚本里再document.createElement('script')或document.write("<script>...</script>") 仍被禁止
localStorage、fetch、top.location 为什么还是能调用
不是它们“能调用”,而是你误开了高危权限组合。沙箱里这些 API 默认全部不可用,但某些 token 组合会实质性绕过隔离。
-
localStorage在沙箱中默认不可读写;即使开了allow-scripts,localStorage.length仍为 0,DevTools 显示(inactive)是正常表现 -
fetch()能发请求,但响应体是否可读取决于是否开了allow-same-origin且目标确实同源;跨域response.text()会抛TypeError: Failed to fetch(非网络错误) -
top.location = 'https://phishing.site'能生效,是因为你加了allow-top-navigation—— 这个 token 允许插件整页跳转,生产环境应绝对避免 -
allow-same-origin和allow-scripts同时存在时,若 iframesrc确实同源,则 localStorage、同源 fetch、cookie 访问可能恢复,但此时沙箱防护已严重削弱
哪些权限组合实际可用,哪些等于没加 sandbox
按最小权限原则配,每个 token 都意味着额外攻击面。堆砌 token 是生产环境最常见失误。
- 只展示带 JS 的广告/图表:
sandbox="allow-scripts allow-popups"(禁表单、禁存储、禁跳转父页) - 嵌入用户填写的问卷:
sandbox="allow-scripts allow-forms allow-popups"(表单提交走 CORS,不碰allow-same-origin) - 加载同源可信子系统:
sandbox="allow-scripts allow-same-origin allow-forms"(必须确认 URL 协议+域名+端口全一致,且服务端返回正确 CORS 头) - 绝对不要写:
sandbox="allow-scripts allow-same-origin allow-popups allow-forms allow-top-navigation"—— 这和没加sandbox几乎等效
真正容易被忽略的是:沙箱 iframe 的 origin 强制变为 "null",所以即使开了 allow-scripts,它也读不到 window.parent、访问不了父页面 DOM;所有通信必须靠 postMessage,且父页接收时必须校验 event.origin,不能依赖 allow-same-origin 绕过验证。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











