首页 > 解决方案 > 使用前端 javascript 文件中的电子 ipcRenderer

问题描述

我正在学习使用 Electron,在尝试让我的应用程序与前端通信时,我知道我需要使用ipcRenderer来获取对 DOM 元素的引用,然后将该信息传递给ipcMain.

我尝试遵循此处此处建议的大部分建议,但是这两个示例都使用require('electron').ipcMain,并且每当我尝试将与前端交互的脚本包含到我的 HTML 中时,自Uncaught ReferenceError: require is not defined. 我一直在寻找几个小时,并没有找到解决方案的运气 - 很明显我做错了什么。

main.js的很简单,我只是创建了我的窗口,然后我创建了一个 ipc 侦听器,如下所示:

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

function createWindow() {
    const window = new BrowserWindow({
        transparent: true,
        frame: false,
        resizable: false,
        center: true,
        width: 410,
        height: 550,
    });
    window.loadFile("index.html");
}

app.whenReady().then(createWindow);

ipc.on('invokeAction', (event, data) => {
    var result = "test result!";
    event.sender.send('actionReply', result);
})

在我希望用来操作 DOM 的文件中,我尝试获取元素 ID,然后添加一个事件侦听器,如下所示:

const ipc = require('electron').ipcRenderer;
const helper = require("./api");


var authenticate_button = ipcRenderer.getElementById("authenticate-button");

var authButton = document.getElementById("authenticate-button");
authButton.addEventListener("click", () => {
    ipc.once('actionReply', (event, response) => {
        console.log("Hello world!");
    })
    ipc.send('invokeAction');
});

function onAuthenticateClick() {
    helper.authenticateLogin(api_public, api_secret, access_public, access_secret);
}

最后,我的 HTML 仅包含一个我希望将事件侦听器附加到的按钮:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Project Test</title>
    <link rel="stylesheet" href="style.css" />
</head>

<body>
    <div class="main-container">
        <button id="authenticate-button" type="submit" onclick="">Authenticate</button>
        <p id="status-label">Not Authenticated</p>
    </div>

    <script src="script.js"></script>
</body>
</html>

如果有人能帮助我指出如何让这个基本功能发挥作用的正确方向,那将非常有帮助!

标签: javascripthtmlnode.jselectron

解决方案


require未定义,因为您没有在nodeIntegration窗口上启用。在您的窗口配置中将其设置为 true:

const window = new BrowserWindow({
  transparent: true,
  frame: false,
  resizable: false,
  center: true,
  width: 410,
  height: 550,
  webPreferences: {
    nodeIntegration: true
  }
})

推荐阅读