Refused to load the script ‘xxxx.js‘ because it violates the following Content Security Policy ...

在使用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程序的主进程中添加如下代码段

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解决方案

猜你喜欢

转载自blog.csdn.net/weixin_43302112/article/details/129471750