我必須檢測關閉瀏覽器事件,所以我關閉用戶的連接。我嘗試了以下方法:
@HostListener('window:beforeunload', ['$event'])
beforeUnloadHandler(event) {
/**
* Post a single object to the server
* Send Beacon API to keep request after browser windowunload event
*/
navigator.sendBeacon(`${this.appConfigService.appConfig.apiUrl}/Account/LogoutDirectly/`);
}
在我的 app.component.ts 上。我在 Chrome 和 Firefox 上都試過了。但它不會觸發任何事情。
資源如下:
Angular 8 HostListener 'window:unload' 如何在卸載前呼叫 API
防止在 Angular 5.x 中關閉瀏覽器選項卡/視窗
uj5u.com熱心網友回復:
解決方案 1: 我已將代碼更改為以下內容:
@HostListener('window:beforeunload')
async ngOnDestroy() {
const userId = this.authenticationService.user?.profile?.sub; // get user id
await this.userService.closeConnection(userId).toPromise(); // sign out user
}
實作 ngOnDestroy 并直接使用異步方法注銷用戶。
解決方案 2: 您還可以使用以下代碼來檢測選項卡何時隱藏并觸發您的代碼:
@HostListener('document:visibilitychange', ['$event'])
visibilitychange() {
this.checkHiddenDocument().then(() => {});
}
async checkHiddenDocument() {
if (document.visibilityState === 'hidden') {
const userId = this.authenticationService.user?.profile?.sub; // get user id
if (!this.authenticationService.isRememberLogin() && userId) {
await this.userService.closeConnections(userId).toPromise();
}
} else {
// add logic
}
}
此解決方案由 Mozilla 開發人員推薦,您可以在以下文章中看到:https : //developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/357767.html
上一篇:執行緒“main”org.openqa.selenium.WebDriverException中的例外:回傳值無法轉換為WebElement:{stacktrace=Backtrace:
