Javascript 使用';退出前';电子中的事件(原子壳)
我有一个应用程序,它需要在退出(比如注销)之前进行API调用。由于我仍然需要访问API调用的一些应用程序数据(redux store),所以我决定在应用程序上收听“退出前”事件 我尝试了以下代码:Javascript 使用';退出前';电子中的事件(原子壳),javascript,event-handling,electron,Javascript,Event Handling,Electron,我有一个应用程序,它需要在退出(比如注销)之前进行API调用。由于我仍然需要访问API调用的一些应用程序数据(redux store),所以我决定在应用程序上收听“退出前”事件 我尝试了以下代码: import {remote} from 'electron'; let loggedout = false; remote.app.on('before-quit', (event) => { if (loggedout) return; // if we are logged out
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);
});
事件似乎从未触发或阻止关机不起作用。
当我将退出前的替换为浏览器窗口模糊
时,事件会触发,代码似乎正常工作
作为参考,我使用Electron 1.2.8(由于某些依赖性,我无法升级)。在退出之前,我已经仔细检查了,事件已经在该版本中
你知道为什么这件事没有被炒吗
提前感谢,节日快乐 有两个问题阻止代码工作:
不知何故,“before quit”事件不会在重新加载进程中触发。(不是main.js)李>
一旦我将eventlistener移动到主进程中,阻止默认设置并没有阻止窗口关闭。这只能通过添加返回false的窗口.onbeforeunload
函数来完成。就像在书中建议的那样
需要注意的是,onbeforeuload
的返回语句不会得到更新。在我的例子中,我首先返回false(以防止窗口关闭)。第二次它没有返回false,但它一直阻止关闭窗口
我通过使用一个不返回false的新函数重写窗口.onbeforeunload
解决了这个问题 我也有同样的问题,这是我的解决方案:
在渲染器中:
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()
})