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

标签 angular google-chrome firefox browser

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

@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/

相关文章:

javascript - 本地开发期间的浏览器缓存管理

firefox - 使用 xdotool 自动刷新网页 - 窗口焦点后不发送 key

angular - 类型 'automaticDataCollectionEnabled' 中缺少属性 'FirebaseApp'

angular - 如何使用 RxJS 跳过可观察值的第一个值?

javascript - Chrome 全屏 API

javascript - 如何检查选项卡加载失败

javascript - 如何使用 Angular2 从控制台输出获取名称到 HTML 页面

Angular 2 : Display different "toolbar" components depending on main navigation

javascript - Chrome 扩展程序 : console. 日志检测器

internet-explorer - Font Awesome无法在Firefox和IE中使用