[英]Using the 'before-quit' event in electron (atom-shell)
我有一個應用程序,它需要在退出之前進行API調用(類似於注銷)。 由於我仍需要訪問某些應用程序數據(redux存儲)以進行API調用,因此我決定在應用程序上偵聽“退出前”事件。
我嘗試了以下代碼:
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);
});
該事件似乎永遠不會觸發或阻止關機無法正常工作。 當我用browser-window-blur
替換before-quit
事件時,該事件確實觸發,並且代碼似乎可以正常工作。
作為參考,我使用Electron 1.2.8(由於某些依賴關系,我無法升級)。 我已經仔細檢查before-quit
事件已在該版本中實現 。
任何想法為何此事件似乎沒有被解雇?
在此先感謝您,節日快樂!
我有同樣的問題,這是我的解決方案:
在渲染器中:
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()
})
有兩個導致代碼無法正常工作的問題:
window.onbeforeunload
函數來完成。 就像在這個線程中建議的那樣。 一個警告是onbeforeunload
的return語句不會被更新。 就我而言,我首先返回false(以防止關閉窗口)。 第二次它沒有返回false,但是一直阻止關閉窗口。
我通過使用不返回false的新函數覆蓋window.onbeforeunload
解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.