gpt4 book ai didi

javascript - ipcRenderer.send和sendSync无法从预加载到主要状态

转载 作者:行者123 更新时间:2023-12-03 12:24:14 27 4
gpt4 key购买 nike

我正在做我的第一个 Electron 应用程序-使用Git中的 Electron 快速启动代码。
我无法将事件从preload.js发送到main.js

我成功地将邮件从main.js发送到preload.js-使用
在main.js中发送mainWindow.webContents.send,在preload.js中发送ipcRenderer.on。
反过来,我在做这件事时遇到了麻烦。

请注意,调整大小事件可以正常工作,并且可以在main.js中正常接收

preload.js:

const {ipcRenderer} = require('electron')

window.addEventListener('DOMContentLoaded', () => {

// Wait for button click to send event
const button = document.getElementById('clickme');
button.addEventListener('click', (event) =>{
console.log('Preload.Click')
// Send Async - Trial #1 - NOT WORKING !!!!!
ipcRenderer.send('asynchronous-message', 'ping')

})
console.log("preload.js DOMContentLoaded");
})



main.js:

const {app, BrowserWindow, dialog} = require('electron')
const path = require('path')

app.on('ready', createWindow)

// Never gets Called - WHY !!!!
app.on('asynchronous-message', (event, arg) => {
console.log('asynchronous-message received ')
// event.sender.send('asynchronous-reply', 'pong')
})

let mainWindow

console.log("\nmain.js starts");

function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true
}
})
mainWindow.loadFile('index.html')
mainWindow.webContents.openDevTools()
mainWindow.on('closed', function () {
mainWindow = null
})

console.log("listen mainWindow.on('resize') >> works");
mainWindow.on('resize', (event, text) => {
console.log("resize ", mainWindow.getSize());
});
} // createWindow

I was expecting the ipcRenderer.send in preload.js to trigger the event 'on' in main.js displaying the message: 'asynchronous-message received'. - Never happens.
I tried sendSync - it hangs the preload.js program.
What am i doing wrong ?

Thanks

最佳答案

是的,因为需要监听ipcMain事件的asynchronous-message而不是app!

您的main.js应该是这样的:

const { app, BrowserWindow, dialog, ipcMain } = require("electron");
const path = require("path");

app.on("ready", createWindow);

// app.on("asynchronous-message", (event, arg) => {// Wrong

ipcMain.on("asynchronous-message", (event, arg) => {
console.log("asynchronous-message received ");
// event.sender.send('asynchronous-reply', 'pong')
});

let mainWindow;

console.log("\nmain.js starts");

关于javascript - ipcRenderer.send和sendSync无法从预加载到主要状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57641033/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com