首页 > 解决方案 > 关闭子窗口时主窗口引用变为空

问题描述

在我的main.js中,我通常创建我的主窗口(let mainWin = null在启动时初始化),当按下某个按钮时,我添加子窗口。

let createNoteWin = null;

function createNoteEditWindow() {
    createNoteWin = new BrowserWindow({ parent:mainWin, modal: true, width: 350, height: 500 , frame: false, show: false});
    createNoteWin.on('close', function() {mainWin = null});
    createNoteWin.loadFile('src/addNote.html');
    createNoteWin.isResizable = false;
    //createNoteWin.webContents.openDevTools();
}

ipcMain.on('open-noteedit-window', function newNoteWindowIPC(event, arg) {  
    createNoteEditWindow();
    createNoteWin.show();
})

但是,当我关闭我的子窗口时,一旦按下另一个按钮,对我的主窗口的引用突然变成null

ipcMain.on('close-noteedit-window', function closeNoteeditWindowIPC(event, arg) {
    mainWin.webContents //works fine
    createNoteWin.close(createNoteWin);
    mainWin.webContents; //throws an error since mainWin is null now, for some reason
})

有谁知道为什么/如何发生这种情况?

标签: javascriptnode.jselectron

解决方案


在第 5 行,您所做的正是您所抱怨的:

    createNoteWin.on('close', function() {mainWin = null});

这设置mainWinnull(“对我的主窗口的引用突然变为空”)。也许你的意思是这个?

    createNoteWin.on('close', function() {createNoteWin = null});

推荐阅读