Angular无法直接区分刷新事件和关闭浏览器/关闭选项卡事件,因此需要通过window对象的beforeunload事件和unload事件来实现区分。
在AppComponent的构造
函数
中,我们可以监听window对象的beforeunload和unload事件:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
export class AppComponent {
constructor() {
window.addEventListener('beforeunload', (event) => {
// 在window关闭之前执行的代码
window.addEventListener('unload', (event) => {
// 在window关闭后执行的代码
在beforeunload事件中,我们可以设置一个变量,以便在unload事件中使用它来判断用户是刷新页面还是关闭浏览器/关闭选项卡:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
export class AppComponent {
private isRefresh: boolean;
constructor() {
window.addEventListener('beforeunload', (event) => {
// 在window关闭之前执行的代码
this.isRefresh = true;
window.addEventListener('unload', (event) => {
// 在window关闭后执行的代码
if (this.isRefresh) {
console.log('刷新页面');
} else {
console.log('关闭浏览器/关闭选项卡');