javascript - ipcRenderer 数据未发送到 Electron 中的 ipcMain
问题描述
我最近开始使用电子开发桌面应用程序。
我想在按钮单击事件中从 index.html 向 main.js 发送表单详细信息。我在 index.js 中的按钮上添加了一个监听器。在线搜索,发现我必须在 main.js 中使用ipcMain,在 index.js 中使用ipcRenderer但数据没有发送到 ipcMain 。
如何在 main.js 中获取表单数据?
在 index.html 中
<div class="btn-div fld">
<button id="loginButton" class="btn btn-primary st-btn" type="submit" name="button">Login</button>
</div>
<script src="index.js" charset="utf-8"></script>
在 index.js 中
document.querySelector("#loginButton").addEventListener('click', function(){
userDetails = document.getElementById('login');
username = userDetails.username.value;
password = userDetails.password.value;
console.log("Hello");
const {ipcRenderer} = require('electron');
ipcRenderer.send('asynchronous-message', username);
})
在 main.js
const { app, BrowserWindow , ipcMain } = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
console.log( arg );
});
解决方案
在使用where is an object在电子中创建浏览器窗口时。将对象定义为: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;
在您添加的代码段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>
如果您是第一次这样做,这有点困难。我添加了更多文章来帮助您消除困惑:
StackOverflow Relation 上的相关答案
与 NodeJS 中的 socket.io 通信
推荐阅读
- apache - apache2:错误:模块未正确启用
- forms - 类别下拉列表获取的内容更多,然后 laravel 5 中的标题不起作用
- python - 使用制表和新行生成格式良好的 Flask 表单输出
- prolog - 如何在 Prolog 中进行假设
- php - mysqli_stmt 函数的正确顺序是什么(如果有)
- powershell - 用于创建多个快捷方式的 Foreach 循环未按预期工作
- linux - 如何在终端中搜索结束/开始/包含某个字母的文件?
- docker - Logstash config 每天按数据列提供的日期输出索引
- kubernetes - coredns 容器仅在一个主服务器上运行
- ruby-on-rails - 如何在创建方面运算符的数组上查找 id