【问题标题】:Using the electron ipcRenderer from a front-end javascript file使用前端 javascript 文件中的电子 ipcRenderer
【发布时间】:2020-10-07 12:39:15
【问题描述】:

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

我尝试遵循建议的大部分建议 herehere,但是这两个示例都使用 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>

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

【问题讨论】:

标签: javascript html node.js electron


【解决方案1】:

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

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

【讨论】:

  • 这绝对是一个有效的答案 - 并且可能是正确的答案,但出于好奇,如果没有节点集成就不可能吗?有人告诉我启用此功能会产生安全问题。
  • @primelf 是真的,正如security guide 所说,在所有加载远程内容的渲染器中启用nodeIntegration 如果您不知道自己在做什么(例如禁用webSecurity 和其他类似的东西)。如果你没有在windows中启用nodeIntegration,你只能在主进程中使用require,并且必须从windows向主进程发送IPC消息来做任何需要require的事情。
猜你喜欢
  • 2020-11-11
  • 2019-10-23
  • 2021-08-11
  • 1970-01-01
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-02
相关资源
最近更新 更多