是被拦截了;浏览器在HTML解析阶段静默丢弃违反CSP或跨域策略的脚本,不执行也不触发error事件,仅在控制台输出Refused to load script等CSP拒绝日志。

浏览器控制台里看不到第三方 script 报错,是不是被拦截了?
不是“看不到”,而是根本没执行——现代浏览器对违反 CSP 或跨域策略的脚本会静默丢弃,连 error 事件都不触发。你刷新页面后在控制台搜 Refused to load script 或 Content Security Policy,大概率能翻到类似这样的日志:Refused to load the script 'https://cdn.example.com/widget.js' because it violates the following Content Security Policy directive: "script-src 'self'"。这类拦截发生在解析 HTML 阶段,早于 JS 执行,所以常规的 window.onerror 或 addEventListener('error', ...) 捕不到。
如何主动监听 script 标签加载失败?
靠 onerror 属性或 error 事件监听是可行的,但仅限于已插入 DOM 的 <script></script> 元素,且只对网络失败、MIME 类型错误等底层加载问题有效,对 CSP、sandbox、CORS 等安全策略拦截无效。
<script src="https://third-party.com/lib.js" onerror="console.warn('加载失败:', this.src)"></script>- 动态创建时加监听:
const s = document.createElement('script');<br>s.src = 'https://third-party.com/widget.js';<br>s.onerror = () => console.error('script 加载被拒,检查 CSP 或域名白名单');<br>document.head.appendChild(s); - 注意:如果脚本因 sandbox 或 iframe 限制被拒(比如在 sandboxed iframe 里尝试执行 script),这个监听也收不到,因为 script 根本不会被解析
iframe 内嵌第三方内容时,怎么确认 sandbox 是否生效?
直接看渲染后的 iframe 元素属性:getComputedStyle(document.querySelector('iframe')).getPropertyValue('content') 没用;正确方式是检查元素本身:document.querySelector('iframe').sandbox 返回的是一个 DOMTokenList,里面包含所有启用的权限。常见误操作是写了 sandbox="" 却没显式添加权限,结果等于全禁——此时 sandbox.value 是空字符串,sandbox.length 为 0,iframe 内 JS、表单、插件、弹窗、顶级导航全部失效。
- 必须显式声明才放开:比如
sandbox="allow-scripts allow-same-origin"才允许执行 JS 并访问父页面 -
allow-scripts不等于可调用parent—— 还得配allow-same-origin,否则跨域 iframe 里 JS 一碰parent就报Blocked a frame with origin ... from accessing a cross-origin frame - Chrome DevTools 的 Elements 面板里右键 iframe → “Break on” → “Attribute modifications”,能实时捕获 sandbox 属性被 JS 动态修改的时刻
CSP 报错太散,怎么集中监控?
靠人工刷控制台不现实。把 <meta http-equiv="Content-Security-Policy" content="..."> 改成 HTTP 响应头,并加上 report-uri 或 report-to,让浏览器自动上报违规详情:
立即学习“前端免费学习笔记(深入)”;
Content-Security-Policy: script-src 'self'; report-to csp-endpoint<br>Report-To: {"group":"csp-endpoint","max_age":10886400,"endpoints":[{"url":"https://your-api.com/csp-report"}]}
上报体里会带 violated-directive、blocked-uri、line-number,比控制台日志完整得多。注意:Firefox 和 Safari 对 report-to 支持不稳定,生产环境建议 fallback 到 report-uri(已废弃但兼容性好)。
真正容易被忽略的是:CSP 的 script-src 对内联事件(如 onclick="...")、javascript: 伪协议、eval() 的拦截,不会出现在控制台,也不会触发 report-uri —— 它们属于“语法级拒绝”,浏览器压根不解析那行代码。这时候只能靠 Linter(如 ESLint 的 no-inline-script 规则)和构建时扫描 HTML 源码来提前发现。



















