javascript - 使用前端 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>
如果有人能帮助我指出如何让这个基本功能发挥作用的正确方向,那将非常有帮助!
解决方案
require
未定义,因为您没有在nodeIntegration
窗口上启用。在您的窗口配置中将其设置为 true:
const window = new BrowserWindow({
transparent: true,
frame: false,
resizable: false,
center: true,
width: 410,
height: 550,
webPreferences: {
nodeIntegration: true
}
})
推荐阅读
- c# - C# Caliburn Micro 管理窗口/视图
- python - 返回函数是干什么用的?
- mysql - 如何在 MySQL 视图中安全地将名称转换为“经过清理的别名”?
- google-bigquery - BigQuery API 可以使用 create_table()(表插入)覆盖现有表/视图吗?
- c - 代码块运行我的代码并提供所需的输出,但随后说 link.exe 已停止工作
- powershell - Get-Command -Module MicrosoftTeams 不包括 Get-TeamChannelUser cmdlet
- javascript - 无法将字符串转换为数字
- python - Gurobi 多目标函数分层退化
- c++ - 带有“”的字符串标记化,在“.”处中断
- javascript - 如何使用 jquery 获取 php 回显