关闭最后一个选项卡后重定向至注销链接



根据要求,当用户关闭浏览器上的最后一个选项卡时,我必须注销他。

ngOnInit() {
let counter: any = this.cookieService.get('screenCounterCookie');
counter ? ++counter : (counter = '1');
this.cookieService.set('screenCounterCookie', counter);
}

@HostListener('window:beforeunload', ['$event'])
ngOnDestroy() {
let counter: any = this.cookieService.get('screenCounterCookie');
if (counter > 1) {
--counter;
this.cookieService.set('screenCounterCookie', counter);
} else {
this.cookieService.delete('screenCounterCookie');
window.open(environment.cognitoLogoutURL);
}
}

行为不稳定。有时它会减少计数器,有时却不会。此外,我必须在这里处理刷新、多个选项卡关闭和浏览器关闭逻辑。

我该如何实现它?

保留选项卡总数:https://jsbin.com/mipanuro/1/edit?html,js,输出(参考此(

方法1(将进行POST调用(:

使用Beacon API(navigator.sendBeacon()(。这将在后台发生。

方法2(也适用于GET调用(:

使用fetchkeep-alive

方法3(Websocket(:

每隔几分钟左右Ping一次你的后端。如果没有Ping,后端可能会使你的会话无效。

在不使用ngOnDestroy的情况下,我对您的逻辑做了一些改进。我试过了,似乎有效。

import { Component } from '@angular/core'
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
constructor() {
const counter = localStorage.getItem('screenCounterCookie') || 0
localStorage.setItem('screenCounterCookie', (Number(counter) + 1).toString())
window.addEventListener('beforeunload', () => {
const counter: number = Number(localStorage.getItem('screenCounterCookie')) - 1
localStorage.setItem('screenCounterCookie', counter.toString())
if (counter <= 0) {
localStorage.removeItem('screenCounterCookie')
console.log('logout')
// Your logout
}
})
}
}

我能想到的实现这一点的唯一可靠方法是使用websocket和keep-alive概念。或者手动定期戳服务器以重置计时器,如果计时器用完,该计时器将注销用户。

你不能以跨平台的方式信任浏览器,让你在浏览器关闭或用户断电时触发事件。

最新更新