在使用Electron封装一些模块的时候,出现以下错误:
Refused to load the script ‘https://unpkg.com/xxxx.js’ because it violates the following Content Security Policy directive: “script-src ‘self’ ‘unsafe-eval’ ‘unsafe-inline’ data:”. Note that ‘script-src-elem’ was not explicitly set, so ‘script-src’ is used as a fallback.
这是由于Electron为了防止出现XSS攻击,阻止了该网站资源的加载,我们设置允许加载即可。
解决方法
例如,我们当前被禁止的xxxx.js
来自https://unpkg.com
那么我们可以在electron程序的主进程中添加如下代码段文章来源:https://www.toymoban.com/news/detail-698538.html
app.on('ready', () => {
createWindow()
session.defaultSession.webRequest.onHeadersReceived((details: Electron.OnHeadersReceivedListenerDetails, callback: (headersReceivedResponse: Electron.HeadersReceivedResponse) => void) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Content-Security-Policy': ['default-src \'self\' \'unsafe-inline\' \'unsafe-eval\' https://unpkg.com'] // 注意这里的https://unpkg.com
}
})
})
});
官方详解:CSP解决方案文章来源地址https://www.toymoban.com/news/detail-698538.html
到了这里,关于Refused to load the script ‘xxxx.js‘ because it violates the following Content Security Policy ...的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!