首页 > 解决方案 > 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 );
});

标签: javascriptnode.jselectron

解决方案


在使用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 通信


推荐阅读