我有一个应用程序需要在退出之前进行API调用(类似注销)。因为我仍然需要访问API调用的一些应用程序数据(redux商店),所以我决定听取之前的退出' app上的活动。
我尝试了以下代码:
import {remote} from 'electron';
let loggedout = false;
remote.app.on('before-quit', (event) => {
if (loggedout) return; // if we are logged out just quit.
console.warn('users tries to quit');
// prevent the default which should cancel the quit
event.preventDefault();
// in the place of the setTimout will be an API call
setTimeout(() => {
// if api call was a success
if (true) {
loggedout = true;
remote.app.quit();
} else {
// tell the user log-out was not successfull. retry and quit after second try.
}
}, 1000);
});
事件似乎永远不会触发或阻止关机不起作用。
当我用before-quit
替换browser-window-blur
时,事件会触发,代码似乎有效。
作为参考,我使用Electron 1.2.8(由于某些依赖性,我无法升级)。我已经进行了双重检查,before-quit
事件在该版本中已经implemented。
为什么这个事件似乎没有被解雇?
先谢谢你,祝节日快乐!
答案 0 :(得分:3)
我遇到了同样的问题,这是我的解决方案:
在渲染器中:
const { ipcRenderer } = require('electron')
window._saved = false
window.onbeforeunload = (e) => {
if (!window.saved) {
callSaveAPI(() => {
// success? quit the app
window._saved = true
ipcRenderer.send('app_quit')
window.onbeforeunload = null
})
}
e.returnValue = false
}
主要:
const { ipcMain } = require('electron')
// listen the 'app_quit' event
ipcMain.on('app_quit', (event, info) => {
app.quit()
})
答案 1 :(得分:0)
有两个问题妨碍了代码的运行:
window.onbeforeunload
函数来完成。与this thread中的建议一样。有一点需要注意,onbeforeunload
的return语句不会更新。在我的情况下,我首先返回false(以防止关闭窗口)。第二次没有返回假,但它一直阻止关闭窗口。
我通过使用一个没有返回false的新函数覆盖window.onbeforeunload
来解决这个问题。