Electron中Refused to execute inline script because it violates the following Content Security Policy directive: "scriptsrc 'self'".

不只是Electron页面,CSP(Content Security Policy)对于普通浏览器一样生效。

方法一: 去掉Content Security Policy

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-HiMSsnVwNlOS+BOeJa0RC003iWmHPCFbSrspL9cPFck='), or a nonce ('nonce-...') is required to enable inline execution.

删除

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title></title>
  </head>
  <body>
    <script>
(省略号)
    </script>
  </body>
</html>

中的

    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">

即可解决。但是会弱化应用的安全性:

Electron Security Warning (Insecure Content-Security-Policy) This renderer process has either no Content Security
    Policy set or a policy with "unsafe-eval" enabled. This exposes users of
    this app to unnecessary security risks.

For more information and help, consult
https://electronjs.org/docs/tutorial/security.
This warning will not show up
once the app is packaged.

方法二:不采用内联

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title></title>
  </head>
  <body>
    <script src="render.js"></script>
  </body>
</html>

CSP为什么禁止执行inline script?

参考:
https://stackoverflow.com/questions/46256983/script-causes-refused-to-execute-inline-script-either-the-unsafe-inline-keyw

https://developers.google.com/web/fundamentals/security/csp/#if_you_absolutely_must_use_it

浅谈XSS攻击的那些事(附常用绕过姿势)https://zhuanlan.zhihu.com/p/26177815

内联代码被视为是有害的。

不过,基于来源的白名单无法解决 XSS 攻击带来的最大威胁: 内联脚本注入。如果攻击者可以注入一个 script 标记,在标记中直接包含一些恶意的负载(<script>sendMyDataToEvilDotCom();</script>),则浏览器将无法将它与合法内联脚本标记区分开来。CSP 可通过完全禁止内联脚本来解决此问题: 这是唯一确定有效的方式。(……此处省略N段示例代码……)除了能够更好地配合 CSP 外,重写的代码还具有许多优势;无论您是否使用 CSP,这都是最佳做法。 内联 JavaScript 混合结构和行为的方式正是您不应采用的方式。使用外部资源,浏览器更容易缓存,开发者也更容易理解,并有助于编译和压缩。如果您将代码移入外部资源,那么您可以编写更好的代码。 以相同方式处理内联样式: style 属性和 style 标记都应合并到外部样式表,以防范可通过 CSS 实现的各种极其狡猾的 数据渗漏方法。

例如,你的网站有一个实时显示用户留言的功能,如果有个用户留言为

<script>一段恶意的代码,将可能被运行在其它客户端上,浏览器无法分辨</script>

这样子,“浏览器将无法将它与合法内联脚本标记区分开来”。

方法三:修改CSP,列出允许执行的脚本代码的Hash值

参考:http://www.ruanyifeng.com/blog/2016/09/csp.html

nonce值的例子就不试了,因为貌似需要服务端的配合。。。。。。。。。。。。。

修改CSP,添加对应脚本的Hash值:

script-src 'self' 'sha256-7+h+PlvW2r7C/54Jfw3CKKxxm09qDfh5XfqJDZKp1t0='

Hash值对应的代码如下:

    <script>
      console.log("dasdas");
    </script>

这样这段inline script就可以顺利执行了。

原文地址:https://www.cnblogs.com/xkxf/p/15553510.html