我有一个带有NodeJS和Express的Electron应用程序 . 我有一个文件(app.js)中的主进程代码和另一个文件(router.js)中的路由 .
主文件创建主窗口:
mainWindow = new BrowserWindow({width: 1280, height: 800, icon: iconPath});
每当您单击应用程序中的pdf文档链接时,routes文件都会创建一个新窗口:
router.get('/docs/:module/:type/:file', function(req, res) {
openPDF(req.params.module,req.params.type,req.params.file);
res.end();
});
// open pdf's in a new window
let newWindow;
const openPDF = function(module,filetype,filename) {
let file = 'file:///' + __dirname + '/app/docs/' + module + '/' + filetype + '/' + filename;
let newWindow = new BrowserWindow({
width: 800,
height: 600,
icon: iconPath,
webPreferences: {
nodeIntegration: false
}
});
newWindow.setMenu(null);
// newWindow.webContents.openDevTools();
const param = qs.stringify({file: file});
newWindow.loadURL('file://' + __dirname + '/app/pdfjs/web/viewer.html?' + param);
newWindow.on('closed', function() {
newWindow = null;
});
}
当我关闭主窗口时,我想要关闭任何其他打开的窗口 . 我一直在努力实现这个困难(两个窗口都在主流程中,所以我不能使用IPC . )然后我意识到如果我在主窗口调用app.quit()关闭它关闭所有其他窗口:
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
// quitting the app on main window close will close any other open windows
app.quit();
})
我的问题是这是否是一件坏事 . 它会在没有任何用户输入的情况下终止所有打开的窗口,但是没有未保存的工作可能会丢失,因为所有新窗口都是无法编辑的pdf .
2 回答
您应该考虑使用像Redux或Flux这样的状态容器框架来管理关闭 . 这样,当您收到用户的关闭信号时,您可以发送信号以确保:
如果用户的数据未保存,则提示用户
如果您愿意,将应用程序的配置数据缓冲到文件中(在下次启动时从之前的状态恢复)
然后运行
app.quit()
,以确保安全退出除此之外,如果您的应用程序不需要安全关闭,那么
app.quit
本身就是关闭您的电子应用程序的完美方式 .几件事:
首先,你说"both windows are in the main process so I can't use IPC to the best of my knowledge."实际上,这不是真的 . 使用
BrowserWindow
本身启动另一个进程 . 在您生成BrowserWindow的Electron生态系统(实际上是具有Electron shell UI和API附加组件的Node环境)中,您正在创建新的渲染过程,并且每个渲染过程都具有可供主要和渲染过程访问的IPC通道另一个 .其次,你询问在mainWindow上的
'close'
事件中使用app.quit()
(“我的问题是这是否是一件坏事 . ”) . 正如您所说,只要您不担心清理窗口/进程中的任何数据,这样做就可以了 . 即使你确实需要清理一些东西,你也可以在'close'
事件函数中处理它 . 所以,不要担心,这不是一件坏事 .