[英]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.