最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot prevent window close in electron - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Jan 6, 2017 at 10:39 Casper Thule HansenCasper Thule Hansen 1,5502 gold badges19 silver badges38 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 9

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 === 0 && win.destroy()
})

In Electron version 11.4.12, i did like this

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

评论列表(0)

  1. 暂无评论