angular - 检测关闭浏览器 Angular 12 的事件

我必须检测关闭浏览器事件,以便关闭用户的连接。 我尝试了以下方法:

@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' how to make API call before unload

Prevent closing browser tab/window in Angular 5.x

最佳答案

解决方案 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

关于angular - 检测关闭浏览器 Angular 12 的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69925187/

相关文章:

unit-testing - 使用 Jest 测试 Vue3 组件时如何模拟计算属性

python - IPywidgets 观察包裹在一个类中时不起作用

c# - 当我更改继承类中同名方法的代码时,我不需要使用属性覆盖和虚拟。这是为什么?

json - 通过 Postman 使用 PUT 请求更新 Contentful 帖子

python - 一段时间后 Discord api websocket 网关连接断开

android - 加载 flutter 时去除图像中的白色闪烁

jooq - jooq record 取数据时是否使用列索引?

python - 如何自定义条形注释以不显示选定值

amazon-web-services - AWS CodePipeline 角色无权在阶段的 "a

c# - 由于 XmlSerialization (sgen.exe) 无法在 Visual Stu