简体   繁体   中英

Cannot prevent window close in electron

I have a renderer process, let's call it RP. On a button click, it opens a browserwindow (BW).

Now when close is clicked on BW, I would like to catch this close event in RP and prevent it.

I am experiencing, that the window is closed, before the close event is called in RP.

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. But I want the RP to control whether the window closes or not.

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

It is not possible, because processes opening the browser window is a renderer process, it is invoked via electron.remote, and therefore processed async. 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

In Electron ^15, do:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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