简体   繁体   English

无法阻止电子窗口关闭

[英]Cannot prevent window close in electron

I have a renderer process, let's call it RP.我有一个渲染器进程,我们称之为 RP。 On a button click, it opens a browserwindow (BW).单击按钮时,它会打开一个浏览器窗口 (BW)。

Now when close is clicked on BW, I would like to catch this close event in RP and prevent it.现在,当在 BW 上单击关闭时,我想在 RP 中捕获此关闭事件并阻止它。

I am experiencing, that the window is closed, before the close event is called in RP.我正在经历,在 RP 中调用close事件之前,窗口已关闭。

Code:代码:

bw.on("close", (e: Electron.Event) => hideWindow(e));
let hideWindow = (e: Electron.Event) => {
    e.preventDefault();
    bw.hide();
    return false;
  }

What am I doing wrong?我究竟做错了什么?

I am aware, that in bw I can use beforeunload, which works.我知道,在 bw 中我可以使用 beforeunload,这很有效。 But I want the RP to control whether the window closes or not.但我希望 RP 控制窗口是否关闭。

Here is how you can prevent the closing: 以下是阻止关闭的方法:

after lots of trials I came up with a solution: 经过大量试验,我想出了一个解决方案:

// 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
  }  
};

Found in docs: event-close and destroy 在docs中找到: event-closedestroy

It is not possible, because processes opening the browser window is a renderer process, it is invoked via electron.remote, and therefore processed async. 这是不可能的,因为打开浏览器窗口的进程是渲染器进程,它通过electron.remote调用,因此处理为异步。 Because of this, the window is closed before the close event is processed. 因此,在处理关闭事件之前关闭窗口。 In case the process opening the browserwindow was the main process, then it would be fine. 如果打开浏览器窗口的进程是主进程,那就没关系了。

This shows the case: https://github.com/CThuleHansen/windowHide And here is a longer discussion of the issue: https://discuss.atom.io/t/close-event-for-window-being-fired-after-window-has-been-closed/37863/4 这显示了这种情况: https//github.com/CThuleHansen/windowHide这是对该问题的更长时间的讨论: https//discuss.atom.io/t/close-event-for-window-being-fired-后窗口过气闭/四分之三万七千八百六十三

In Electron ^15, do:在电子 ^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()
})

In Electron version 11.4.12, i did like this在 Electron 版本 11.4.12 中,我确实喜欢这个

mainWindow.on('close', (e: any) => {
    e.preventDefault();
    mainWindow?.hide();
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM