Electron 中的beforeunload
事件与浏览器中的行为不同。 如果我返回一个字符串,它不会显示在确认对话框中。 我在BrowserWindow
看到了使用beforeunload
的示例,并且在其中您在评论中提到可以显示确认对话框:
// 您也可以使用对话框 API 让用户确认关闭应用程序
对话 API 不是只适用于主进程吗?
复制正常浏览器行为的最简单方法是什么?
没关系。 我想到了。
为了将来参考,这里有一个例子:
window.onbeforeunload = function(e) {
var remote = require('remote');
var dialog = remote.require('dialog');
var choice = dialog.showMessageBox(
remote.getCurrentWindow(),
{
type: 'question',
buttons: ['Yes', 'No'],
title: 'Confirm',
message: 'Are you sure you want to quit?'
});
return choice === 0;
};
你好(:
上述解决方案对我不起作用。
因为它仍然需要浏览器的“onbeforeunload”......
任何的想法?
@shneorasa我知道你问这个问题已经几个月了(你现在可能已经找到了一个解决方案),但是对于那些在未来寻找解决方案的人来说,这里有一个更好的方法来处理这个问题,而不是使用window.onbeforeload
。
beforeunload
事件被覆盖可能会扰乱未来的对话框,破坏您的应用程序。 相反,您可以像我所做的那样在您的应用程序中存储一个简单的布尔值:
// Inside main/index.js
import { app, BrowserWindow, dialog } from 'electron'
app.showExitPrompt = true
有了这一点,你可以中断close
的您的活动BrowserWindow
如下:
// Inside main/index.js, where BrowserWindow is initialized
mainWindow.on('close', (e) => {
if (app.showExitPrompt) {
e.preventDefault() // Prevents the window from closing
dialog.showMessageBox({
type: 'question',
buttons: ['Yes', 'No'],
title: 'Confirm',
message: 'Unsaved data will be lost. Are you sure you want to quit?'
}, function (response) {
if (response === 0) { // Runs the following if 'Yes' is clicked
app.showExitPrompt = false
mainWindow.close()
}
})
}
})
我已经使用 Vue.js 在一个 Electron 应用程序中实现了这个解决方案,并且显示/隐藏对话框就像导入app
一样简单:
const { app } = require('electron').remote
并覆盖存储的布尔值:
app.showExitPrompt = true
最有用的评论
@shneorasa我知道你问这个问题已经几个月了(你现在可能已经找到了一个解决方案),但是对于那些在未来寻找解决方案的人来说,这里有一个更好的方法来处理这个问题,而不是使用
window.onbeforeload
。beforeunload
事件被覆盖可能会扰乱未来的对话框,破坏您的应用程序。 相反,您可以像我所做的那样在您的应用程序中存储一个简单的布尔值:有了这一点,你可以中断
close
的您的活动BrowserWindow
如下:我已经使用 Vue.js 在一个 Electron 应用程序中实现了这个解决方案,并且显示/隐藏对话框就像导入
app
一样简单:并覆盖存储的布尔值: