繁体   English   中英

Electron.js 防止窗口有条件地关闭

[英]Electron.js prevent windows close conditionally

我想问用户他是否真的想关闭一个电子应用程序。

根据文档- 我尝试过:

window.onbeforeunload = (e) => {
  const answer = confirm('Do you want to close the application?');
  e.returnValue = answer;
  if (answer) { window.close(); }
};

但无论用户选择什么,我的应用程序仍然关闭。 如何防止有条件地关闭电子应用程序?

我想,我有一个答案。 不应在渲染器进程中调用它。 相反,我们应该在主进程中使用 mainWindow 进行此类操作和“关闭”生命周期方法,该方法将在关闭之前调用。

this.mainWindow.on('close', (e) => {
  const choice = this.dialog.showMessageBox(
    this.mainWindow,
    {
      type: 'question',
      buttons: ['Yes', 'No, hang on', 'third option'],
      title: 'Confirm your actions',
      message: 'Do you really want to close the application?'
    }
  );
  console.log('CHOICE: ', choice);
  if (choice > 0) e.preventDefault();
});

选择 const 将从按钮数组返回答案,因此“是”将作为确认,对于其他选项,我们可以阻止操作。

注意:我已经粘贴了this. 从我的代码中,但是,显然mainWindow是您的BrowserWindow实例,而this.dialog是从 import electron.dialog import electron from 'electron';

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

暂无
暂无

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

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