[英]mainWindow.webContents.send() not received by ipcRenderer.on() function
In the electron main.js I am wanting to send an event from a child Window to a mainWindow.在电子 main.js 中,我想将事件从子窗口发送到主窗口。 The way I thought to do this was by sending an event from childWindow to the Main Process, and the Main Process then sends an event to the mainWindow.
我想这样做的方法是从 childWindow 向 Main Process 发送一个事件,然后 Main Process 向 mainWindow 发送一个事件。
ipcMain.on('submit-form-data', (event, data) => {
if (data) {
console.log('send data to main window')
mainWindow.webContents.send('submitted-form', data)
}
childWindow.hide();
})
The childWindow successfully send it's form data to the main process. childWindow 成功地将它的表单数据发送到主进程。 But when I want the main process to then send that data to the mainWindow, the event is not being picked up.
但是当我希望主进程将该数据发送到 mainWindow 时,该事件没有被接收。 I don't have an idea of what I can try to get this to work.
我不知道我可以尝试什么来让它发挥作用。
index.html in the mainWindow主窗口中的 index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Main Window</title>
<script>
var ipcRenderer = nodeRequire("electron").ipcRenderer;
ipcRenderer.on("submitted-form", function (event, data) {
alert('received data'); // this never gets called :(
});
</script>
Wrap your mainWindow.webContents.send('submitted-form', data);
包装您的
mainWindow.webContents.send('submitted-form', data);
line with mainWindow.webContents.on('did-finish-load', ()=>{});
与
mainWindow.webContents.on('did-finish-load', ()=>{});
. . It solved my problem, hope helps you too.
解决了我的问题,希望对你也有帮助。
mainWindow.webContents.on('did-finish-load', ()=>{
mainWindow.webContents.send('submitted-form', data);
})
It works, you'll need to enable nodeIntegration
on the BrowserWindow and fix the import of ipcRenderer
:它的工作原理,你就需要启用
nodeIntegration
在BrowserWindow和修复的进口ipcRenderer
:
app.js (Main process) app.js (主进程)
const {app,BrowserWindow} = require("electron")
const url = require("url")
const path = require("path")
let mainWindow
app.on("ready", function() {
mainWindow = new BrowserWindow({
width: 500,
height: 300,
webPreferences: {
nodeIntegration: true
}
})
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, "index.html"),
protocol: "file:",
slashes: true
}))
mainWindow.toggleDevTools()
setTimeout(() => {
console.log("sending message from main process")
mainWindow.webContents.send("submitted-form", "hello")
}, 3000)
})
index.html (Renderer process) index.html (渲染器进程)
<!DOCTYPE html>
<html>
<body>
Index with renderer javascript
</body>
<script type="text/javascript">
const { ipcRenderer } = require("electron")
ipcRenderer.on("submitted-form", function (event, data) {
console.log("received data", data)
alert("received data")
});
</script>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.