如何通过 HTML(脚本标签)获取 Electron 应用程序对象?

How do I get a Electron app object through HTML (script tag)?

所以我这里有这个:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Oh no!</title>
</head>
<body>
      <label>Oh dear. A serious error occurred and the app needs to restart. Press the button below to restart.</label>

      <br>
      <button onclick="restart()">Restart</button>

      <script>
        const { app } = require("electron")

        function restart() {
          app.relaunch()
          app.exit()
        }
      </script>
</body>
</html>

现在,当应用程序收到未处理的错误时,这将显示...但是当用户单击按钮时,应用程序不会重新启动,那么我该如何重新启动应用程序?

不使用 preload.js 就无法获取 app 对象,直接获取 app 对象也不安全。有一种方法可以使用 preload.jsipcRenderer 来完成上述操作,它们是纯 Electon API

在electron中(甚至在web开发中),有服务器端代码和浏览器端代码。代码段中脚本标记之间的代码是服务器端代码,将无法在浏览器端执行。

你的服务器端代码在 NodeJS 后端,浏览器端代码是 HTML 页面和它自己的 javascript.

所以要关闭 window(只有 NodeJS 可以做到,即后端),您需要使用 Electron 的 ipcRenderer,它有助于浏览器端之间基于字符串的通信 javascript 和服务器端 javascript.

creating a browser window 在 electron 中使用 new BrowserWindow(options) 其中 options 是一个对象。定义对象为:

options = {
    webPreferences: {
         preload: preload.js, //You need to create a file named preload.js (or any name) in your code
         nodeIntegration: true,
         contextIsolation: false,
    }
}

现在在一个名为 preload.js 的新文件中:

window.ipcRenderer = require('electron').ipcRenderer;

在您的代码段中,您添加了 const { app } ...,应该以这种方式使用对象中的 preload 属性 注入 javascript。

现在在创建浏览器的主要 app.js 文件(无论您命名什么 index.js)中 window:

const ipc = require('electron').ipcMain; //Add to your pre-existing code
ipc.on("close-app", (event, message) => { //"close-app" can be anything but, you need to use the same key in the send message side (later in this answer)
    browserWindow.close(); //If you named the browserwindow as browserWindow
});

现在在您的HTML(即发送消息端)

...
<script>
    window.ipcRenderer("close-app", ""); //Second parameter is used if you want to send some extra message. The extra message can be viewed in the server side from the message parameter in the app.js code (just above this paragraph)
</script>

如果你是第一次做,这有点困难。 我添加了更多文章来帮助您消除困惑:

Relation with socket.io communication in NodeJS