【问题标题】:How do I get a Electron app object through HTML (script tag)?如何通过 HTML(脚本标签)获取 Electron 应用程序对象?
【发布时间】:2021-05-07 12:56:54
【问题描述】:

所以我在这里:

<!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>

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

【问题讨论】:

    标签: node.js electron


    【解决方案1】:

    不使用preload.js 就无法获取app 对象,也不能直接获取app 对象安全。有一种方法可以使用纯 Electon API 的 preload.js 和 ipcRenderer 执行上述操作

    在电子中(甚至在 Web 开发中),有服务器端代码和浏览器端代码。 sn-p中脚本标签之间写的代码是服务器端代码,将无法在浏览器端执行。

    在您的情况下,服务器端代码位于 NodeJS 后端,而浏览器端代码是 HTML 页面及其自己的 javascript。

    所以要关闭窗口(只有 NodeJS 可以这样做,即后端),您需要使用 Electron 的 ipcRenderer,它有助于在浏览器端 javascript 和服务器端 javascript 之间进行基于字符串的通信。

    而creating a browser window 在电子中使用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;
    

    在您的 sn-p 中,您添加了 const { app } ...,应该这样做以使用对象中的 preload 属性注入 javascript。

    现在在您创建浏览器窗口的主 app.js 文件(无论您命名为 index.js)中:

    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>
    

    如果您是第一次这样做,这有点困难。 我添加了更多文章,可以帮助您消除困惑:
    Highlight about server-side and browser-side code
    Relation with socket.io communication in NodeJS

    【讨论】:

    • 非常感谢!我将对此进行测试(大量步骤,哈哈),并在一分钟内回复您。
    • 注意:你不需要预加载,你可以在
    猜你喜欢
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2012-02-06
    相关资源
    最近更新 更多