解决Content Security Policy (CSP)问题
做的一个简单的自动识别图片文字是否一致的程序 引用的百度的OCR 在公司的代码运行正常 在家运行报错了
Refused to apply inline style because it violates the following Content Security Policy directive: “default-src ‘none’”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-QIjW/+aUzfg58HcITJNHkkCTGmLovNUIQbL+Zq2TsIE=’), or a nonce (‘nonce-…’) is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the ‘unsafe-hashes’ keyword is present. Note also that ‘style-src’ was not explicitly set, so ‘default-src’ is used as a fallback. g @ customElements.js:1 customElements.js:1 Refused to apply inline style because it violates the following Content Security Policy directive: “default-src ‘none’”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-QIjW/+aUzfg58HcITJNHkkCTGmLovNUIQbL+Zq2TsIE=’), or a nonce (‘nonce-…’) is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the ‘unsafe-hashes’ keyword is present. Note also that ‘style-src’ was not explicitly set, so ‘default-src’ is used as a fallback. g @ customElements.js:1 prepare.js:1 Refused to execute inline script because it violates the following Content Security Policy directive: “default-src ‘none’”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-3bzWVxQE32IZQKH9eh8KzyHuhXOlMrboDVVBRd0fWTU=’), or a nonce (‘nonce-…’) is required to enable inline execution. Note also that ‘script-src’ was not explicitly set, so ‘default-src’ is used as a fallback. c @ prepare.js:1 (索引):1 Failed to load resource: the server responded with a status of 404 (Not Found)
Content Security Policy (CSP) 的问题把 inline style 和 inline script 全部拦掉了
解决方法
方法 1:关闭 CSP
用 VS Code 的 Live Server 插件或 http-server 跑,不要用直接打开 file://。
再或者在浏览器里启动的时候加上参数关闭 CSP,比如 Chrome:chrome.exe --disable-web-security --user-data-dir=c:\temp\chrome
方法 2:修改 CSP 规则
如果你控制的是自己服务器,可以在响应头里加:
Content-Security-Policy: default-src * ‘unsafe-inline’ ‘unsafe-eval’ data: blob:
这样就允许内联的
方法 3:修改你现在的代码
你现在的代码里有:
这样就不会触发 inline 的 CSP 限制。