我们如何检测用户何时关闭浏览器? [英] How can we detect when user closes browser?
本文介绍了我们如何检测用户何时关闭浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的意思是,我想跟踪用户何时离开应用程序,关闭浏览器或标签页.
I mean, I want to track when a user leaves the app, closing browser or tabs.
Components and Directives有一个名为ngOnDestroy的生命周期挂钩,在销毁组件时会调用它,但是当用户离开应用程序时无法捕获
Components and Directives has a lifecycle hook called ngOnDestroy, which is called when the component is destroyed, but it can't catch when the user leaves the app
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!`);
}
}
如果用户关闭浏览器,则不会执行警报.
If the user closes the browser, the alert is not executed.
推荐答案
您可以像这样收听unload
或beforeunload
事件:
You can listen to the unload
or beforeunload
events like this:
export class AppComponent {
@HostListener('window:unload', [ '$event' ])
unloadHandler(event) {
// ...
}
@HostListener('window:beforeunload', [ '$event' ])
beforeUnloadHandler(event) {
// ...
}
}
另请参见
- Detect browser or tab closing
- https://developer.mozilla.org/de/docs/Web/Events/unload
这篇关于我们如何检测用户何时关闭浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文