gpt4 book ai didi

javascript - 在 Electron 中卸载前确认

转载 作者:行者123 更新时间:2023-11-29 16:05:00 26 4
gpt4 key购买 nike

我知道有数百个问题,例如:“如何防止 Electron 中的关闭事件”或类似的问题。
beforeunload 事件中实现确认框( Electron 消息框)后,我能够关闭我的应用程序并取消关闭事件。由于开发工具始终处于打开状态,因此我没有意识到在关闭开发工具时它不起作用...

window.onbeforeunload = e =>
{
// show a message box with "save", "don't save", and "cancel" button
let warning = remote.dialog.showMessageBox(...)

switch(warning)
{
case 0:
console.log("save");
return;
case 1:
console.log("don't save");
return;
case 2:
console.log("cancel");
return false;
// e.returnValue = "false";
// e.returnValue = false;
}
};

因此,当打开开发工具时,我可以通过保存关闭应用程序,而不保存并取消事件。
关闭开发工具后,取消按钮将不再起作用。

顺便说一句:

window.onbeforeunload = e =>
{
return false;
alert("foo");
};

将取消关闭事件并且显然不会显示消息(无论开发工具是打开还是关闭都无所谓)

window.onbeforeunload = e =>
{
alert("foo");
return false;
};

如果开发工具已打开,则在按确定后将取消关闭事件;如果开发工具已关闭,则将在按确定后关闭应用程序

我故意使用消息框的同步 api,在写这个问题时我发现一个双窗口应用程序 (new remote.BrowserWindow()) 的行为与使用开发工具。

有人知道我该如何解决这个问题吗?
非常感谢

最佳答案

而不是 onbeforeunload 更喜欢使用事件 close。从此事件中,您将能够在整个关闭过程完成之前捕获关闭事件(事件 closed)。使用 close,您将能够控制并在需要完成闭包时停止。

这在您创建 BrowserWindow 时是可能的,最好是在主进程中:

// Create the browser window.
window = new BrowserWindow({});

// Event 'close'
window.on('close', (e) => {
// Do your control here
if (bToStop) {
e.preventDefault();
}
})

// Event 'closed'
window.on('closed', (e) => {
// Fired only if you didn't called e.preventDefault(); above!
})

此外,请注意 e.preventDefault() 函数在整个代码中蔓延。如果您需要回到 Electron 的自然行为,您需要将变量 e.defaultPrevented 切换为 false

实际上,e.preventDefault() 函数似乎正在将变量 e.defaultPrevented 处理为 true,直到对其进行任何更改。

关于javascript - 在 Electron 中卸载前确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45827709/

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