[英]Cannot prevent window close in electron
我有一个渲染器进程,我们称之为 RP。 单击按钮时,它会打开一个浏览器窗口 (BW)。
现在,当在 BW 上单击关闭时,我想在 RP 中捕获此关闭事件并阻止它。
我正在经历,在 RP 中调用close
事件之前,窗口已关闭。
代码:
bw.on("close", (e: Electron.Event) => hideWindow(e));
let hideWindow = (e: Electron.Event) => {
e.preventDefault();
bw.hide();
return false;
}
我究竟做错了什么?
我知道,在 bw 中我可以使用 beforeunload,这很有效。 但我希望 RP 控制窗口是否关闭。
以下是阻止关闭的方法:
经过大量试验,我想出了一个解决方案:
// Prevent Closing when work is running
window.onbeforeunload = (e) => {
e.returnValue = false; // this will *prevent* the closing no matter what value is passed
if(confirm('Do you really want to close the application?')) {
win.destroy(); // this will bypass onbeforeunload and close the app
}
};
在docs中找到: event-close和destroy
这是不可能的,因为打开浏览器窗口的进程是渲染器进程,它通过electron.remote调用,因此处理为异步。 因此,在处理关闭事件之前关闭窗口。 如果打开浏览器窗口的进程是主进程,那就没关系了。
这显示了这种情况: https : //github.com/CThuleHansen/windowHide这是对该问题的更长时间的讨论: https : //discuss.atom.io/t/close-event-for-window-being-fired-后窗口过气闭/四分之三万七千八百六十三
在电子 ^15 中,执行:
win.on('close', async e => {
e.preventDefault()
const { response } = await dialog.showMessageBox(win, {
type: 'question',
title: ' Confirm ',
message: 'Are you sure that you want to close this window?',
buttons: ['Yes', 'No'],
})
response || win.destroy()
})
在 Electron 版本 11.4.12 中,我确实喜欢这个
mainWindow.on('close', (e: any) => {
e.preventDefault();
mainWindow?.hide();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.