带有消息框确认的电子应用程序关闭对话框

Electron app close dialog with message box confirmation

我使用 Electron v13.0.1 来自这个 repo

需要关闭确认,使用这个实现:

win.on('close', function (e) {
    require('electron').dialog.showMessageBox(this, {
        type: 'question',
        buttons: ['Yes', 'No'],
        title: 'Confirm',
        message: 'Are you sure you want to quit?'
    }).then(function (data) {
        if (data.response === 0) {
            e.preventDefault();
        }
    });
});

但是当我点击关闭按钮时,第二次出现对话框,应用程序在没有任何确认或拒绝的情况下关闭。换句话说,对话框不会为关闭创建连词。

我的解决方案有什么问题?

问题是您正在调用异步方法,并且事件函数继续执行并最终 returns,然后再给出任何用户输入。

解决此问题的一种方法是使用 showMessageBoxSync 函数进行同步操作。这将等到用户在继续执行之前选择一个选项。如下所示:

const { dialog } = require('electron');

win.on('close', function (e) {
    let response = dialog.showMessageBoxSync(this, {
        type: 'question',
        buttons: ['Yes', 'No'],
        title: 'Confirm',
        message: 'Are you sure you want to quit?'
    });

    if(response == 1) e.preventDefault();
});