【问题标题】:How can we detect when user closes browser?我们如何检测用户何时关闭浏览器?
【发布时间】:2016-10-05 04:26:52
【问题描述】:

我的意思是,我想跟踪用户何时离开应用、关闭浏览器或标签页。

Components and Directives有一个生命周期钩子,叫做ngOnDestroy,当组件被销毁时调用,但是当用户离开应用时却捕捉不到

import { Component, OnInit } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'app',
  templateUrl: 'app.component.html'
})
export class AppComponent implements OnDestroy {
  constructor() { }

  ngOnDestroy() {
      alert(`I'm leaving the app!`);
  }

}

如果用户关闭浏览器,则不会执行警报。

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以像这样收听unloadbeforeunload 事件:

    export class AppComponent {
      @HostListener('window:unload', [ '$event' ])
      unloadHandler(event) {
        // ...
      }
    
      @HostListener('window:beforeunload', [ '$event' ])
      beforeUnloadHandler(event) {
        // ...
      }
    }
    

    另见

    【讨论】:

    • 只能关闭标签/浏览器。
    • AFAIK 只有unloadbeforeunload。可能有一些技巧或黑客可以获取更多信息,但我对此一无所知。
    • @GünterZöchbauer 上面的方法对我不起作用......我发出警报,但它没有触发......角度版本 2.4.10
    • 永远不会显示警报.. 因为到那时对话框将消失。在开发者工具上放一个断点,这样你就可以看到它被触发了。
    • 这个事件不仅在关闭标签页时也会在刷新页面时触发。
    猜你喜欢
    • 2021-11-06
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    相关资源
    最近更新 更多