Electron刚编写时碰到的两个问题

  1. require is not defined

在这里插入图片描述

经查相关资料,原来官方在5.0版本修改了nodeIntegration的默认值,官方说明如下:

The default values of nodeIntegration and webviewTag are now false to improve security.

解决办法:
修改创建BrowserWindow部分的相关代码,设置属性webPreferences.nodeIntegration为 true


let win = new BrowserWindow({
    webPreferences: {
        nodeIntegration: true
    }
})

  1. Refused to execute inline event handler because it violates the following Content Security Policy directive … 和 Uncaught ReferenceError: process is not defined

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <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>Hello World!</title>
  </head>
  <body>

    <div>
      <h2>Process</h2>
      <button onclick="getProcessInfo()">查看preocess信息</button>
    </div>

    <!-- You can also require other files to run in this process -->
    <script src="./renderer.js"></script>
  </body>
</html>




renderer.js:


function getProcessInfo(){
    console.log("getCPUUsage: ", process.getCPUUsage());
    console.log('env', process.env);
    console.log('arch', process.arch);
    console.log('arch', process.platform);
    console.log('arch', process.versions);
}

直接在html代码中写onclick

会出现以下错误:

error1:Refused to execute inline event handler because it violates the following Content Security Policy directive: “script-src ‘self’”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-…’), or a nonce (‘nonce-…’) is required to enable inline execution.

这时候查阅资料,在 https://stackoverflow.com/questions/36324333/refused-to-execute-inline-event-handler-because-it-violates-csp-sandbox 中找到答案。

解决方法:

首先修改 index.html 文件: 把 查看preocess信息 改成 查看preocess信息

其次修改 renderer.js 文件: 在 function getProcessInfo() 这一句上面添加上 : document.getElementById(“btn”).addEventListener(“click”, getProcessInfo);

修改好后,再次编译运行就没有以上错误了。

猜你喜欢

转载自blog.csdn.net/cainiao1412/article/details/110003963