【问题标题】:Electron IPC communication throwing error?电子 IPC 通信抛出错误?
【发布时间】:2022-11-10 21:59:46
【问题描述】:

我现在解决了几个小时的问题,但我仍然无法弄清楚......

以下是我的代码的一些部分:

main.js

const electron = require('electron');
const { app, BrowserWindow, ipcMain } = electron;

// ...

const createWindow = () => {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true
        },
    });
    
    // and load the index.html of the app.
    mainWindow.loadFile(path.join(__dirname, 'index.html'));
    
    // Open the DevTools.
    mainWindow.webContents.openDevTools();
};

// ...

ipcMain.on("exit", (evt, arg) => {
    app.quit();
});

索引.html

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <button id="exit">Exit</button>
    <script src="index.js"></script>
  </body>
</html>

index.js

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

document.getElementById("exit").addEventListener("click", function(e) {
    ipcRenderer.send("exit");
});

该应用程序应按“退出”按钮关闭。

我得到的错误是:Uncaught ReferenceError: require is not defined

请帮助我正确进行基本的沟通。

我尝试使用 preload.js,但这让它变得更加复杂。

【问题讨论】:

  • 阅读context isolation。也可以在nodeIntegration下添加contextIsolation: false但不推荐
  • 是的,这行得通。但它更多的是一种解决方法,而不是一个干净有效的解决方案

标签: javascript electron ipc


【解决方案1】:

您的 index.js 代码最好作为 preload.js 脚本(见下文)运行,该脚本可以访问 Node API,然后您就不需要节点集成(这可能是一个安全问题)...

main.js

const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
// ...

const createWindow = () => {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        },
    });
    
    // and load the index.html of the app.
    mainWindow.loadFile(path.join(__dirname, 'index.html'));
    
    // Open the DevTools.
    mainWindow.webContents.openDevTools();
};

// ...

ipcMain.on("exit", (evt, arg) => {
    app.quit();
});

preload.js

const { ipcRenderer } = require('electron');

document.getElementById('exit').addEventListener("click", event => {
    ipcRenderer.send('exit');
});

索引.html

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <button id="exit">Exit</button>
  </body>
</html>

【讨论】:

  • 最好在 preload 中使用contextBridge 在渲染器中公开 api。这使得这些函数绑定到窗口并在其他渲染器 js 文件中使用。
猜你喜欢
  • 2018-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 2018-07-01
  • 2012-03-12
  • 2017-07-18
  • 1970-01-01
  • 2020-10-25
相关资源
最近更新 更多