问题描述
根据要求,当用户关闭浏览器上的最后一个选项卡时,我必须注销用户。
10.0.0.1.xip.io resolves to 10.0.0.1
www.10.0.0.1.xip.io resolves to 10.0.0.1
行为不稳定。有时它会减少计数器,有时不会。此外,我必须在这里处理刷新、多个选项卡关闭和浏览器关闭逻辑。
我该如何实施?
解决方法
保持标签总数:https://jsbin.com/mipanuro/1/edit?html,output(参考此)
方法 1(将进行 POST
调用):
使用 BeaconAPI (navigator.sendBeacon()
)。这将在后台发生。
方法 2(也适用于 GET
调用):
使用 fetch
和 keep-alive
方法 3(Websocket):
每隔几分钟左右 Ping 一次您的后端。如果没有 ping,后端可能会使您的会话无效。
,我能想到的实现这一点的唯一可靠方法是使用 websockets 和 keep-alive 的概念。或者手动定期戳服务器以重置计时器,如果计时器用完,该计时器将注销用户。
您不能以跨平台的方式信任浏览器,允许您在浏览器关闭或用户断电时触发事件。
,我在不使用 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
}
})
}
}