我的标题可能无法正确捕捉我的问题,但是我找不到捕捉问题的简洁方法。
问题是这样的:
我有一个由IPC事件触发的BrowserWindow。当BroswerWindow打开时,它会向主进程发送一条消息,以表明已完成加载,然后主进程向其发送一些数据以执行特定任务。完成任务后,用户关闭窗口,并开始执行其他过程。
一切正常,除了应用程序接收到该事件以再次打开BrowserWindow之外,将数据发送到新窗口的事件处理程序抛出错误,表明由于进程已被破坏或重新打开而无法将数据发送到窗口窗口,但包含第一次打开窗口时的所有旧数据,当时我需要的是窗口的新实例。我知道我可以简单地使用javascript拆卸并重新生成原始HTML,但是我觉得必须有更好的方法。这是下面的代码:
main.js
const electron = require ("electron");
const ipcMain = require('electron').ipcMain;
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
function openNewWindow() {
let win = new BrowserWindow({ autoHideMenuBar: true });
win.loadURL(__dirname + '\\new_window.html');
win.webContents.openDevTools()
win.on('closed', function () {
win = null;
})
return win
};
let mainWindow;
app.on('window-all-closed', function () {
if (process.platform != 'darwin') {
app.quit ();
}
});
app.on('ready', function () {
mainWindow = new BrowserWindow ({
title: app.getName() + " - v" + app.getVersion(),
autoHideMenuBar: true
});
mainWindow.loadURL ('file://' + __dirname + '/index.html');
//This event handler opens the new window when it receives the open-new-window event
ipcMain.on('open-new-window', (event,arg) => {
console.log('Arg = ' + arg);
let newWindow = openNewWindow();
//This event handler sends data to the new window when the new window indicates that it is done loading
ipcMain.on('done-loading',(event2,arg2) => {
console.log(arg2);
newWindow.webContents.send('test',arg);
});
});
// Close the application when the window is closed
mainWindow.on ('closed', function() {
mainWindow = null;
});
});
错误消息中对第52行的引用是此行:
newWindow.webContents.send('test',arg);
新窗口打开,但是没有数据发送给它。
问题类似于此问题。
每个open-new-window
事件都会导致您重新订阅新窗口ipcMain
的done-loading
事件,但仍会保留对旧窗口的订阅/关闭。
您不想ipcMain.on("done-loading", ...)
在新窗口处理程序内部执行操作。
您想在窗口处理程序之外执行此操作,而是使用event参数将响应发送回相同的webcontents:
ipcMain.on('open-new-window', (event, arg) => {
openNewWindow();
});
ipcMain.on('done-loading', (event, arg) => {
event.sender.send('test', arg);
});
但是,有一个did-finish-load
事件可以完成您似乎想做的事情:
function openNewWindow() {
let win = new BrowserWindow({ autoHideMenuBar: true });
win.loadURL(__dirname + '\\new_window.html');
win.webContents.once("did-finish-load", () => {
win.webContents.send("test", ...);
});
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句