gpt4 book ai didi

javascript - 当关闭 Electron 中的 BrowserWindow 时,事件监听器继续引用 BrowserWindow

转载 作者:行者123 更新时间:2023-11-28 03:21:40 35 4
gpt4 key购买 nike

我的标题可能没有正确表达我的问题,但我找不到简洁的方法来表达问题。

问题是这样的:

我有一个由 IPC 事件触发的 BrowserWindow。当 BroswerWindow 打开时,它会向主进程发送一条消息,表示它已完成加载,然后主进程会向其发送一些数据来执行特定任务。任务完成后,用户关闭窗口并开始执行不同的进程。

这一切都工作正常,除了应用程序收到该事件以再次打开 BrowserWindow 时,将数据发送到新窗口的事件处理程序会抛出一个错误,表明它无法将数据发送到窗口,因为该过程已被销毁或重新打开窗口,但使用第一次打开窗口时的所有旧数据,而我需要的是窗口的新实例。我知道我可以简单地使用 javascript 来拆除并重新生成原始 HTML,但我觉得必须有更好的方法。下面是代码:

ma​​in.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;
});
});

This is the error that I get when triggering the open-new-window event after closing the new window:

错误消息中对第 52 行的引用是此行:

newWindow.webContents.send('test',arg);

新窗口打开,但没有数据发送到其中。

最佳答案

该问题与 this 问题类似。

每个 open-new-window 事件都会导致您重新订阅 ipcMain 到新窗口的 done-loading 事件,但它仍然维护对旧窗口的订阅/关闭。

您不想在新窗口处理程序内执行 ipcMain.on("done-loading", ...) 操作。

您想在窗口处理程序之外执行此操作,而是使用事件参数将响应发送回相同的 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", ...);
});
};

关于javascript - 当关闭 Electron 中的 BrowserWindow 时,事件监听器继续引用 BrowserWindow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59106580/

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