Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 910
Casper Thule Hansen Avatar asked Jan 06 '17 10:01

Casper Thule Hansen


2 Answers

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

like image 79
chitzui Avatar answered Oct 13 '22 23:10

chitzui


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

like image 30
Casper Thule Hansen Avatar answered Oct 14 '22 00:10

Casper Thule Hansen