如何检查用户是否可以返回浏览器历史记录
2024-03-12 本文已影响0人
熊孩子他哥
如何检查当前是否正处于浏览器历史栈的第一个,然后执行自定义逻辑
方案1:
navigation.canGoBack,可以解决,但是对浏览器的兼容很差
方案2(推荐):
history.go(-1);
var timeout = 100;
var timer = setTimeout(() => {
// 超时进入备选方案,执行你的逻辑
}, timeout);
// 页面销毁,则清除备选方案
addEventListener('pageOnDestroy',()=>{
window.clearTimeout(timer)
})
Angular 实例
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject, interval } from 'rxjs'
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-test-page',
templateUrl: './test-page.component.html',
styleUrls: ['./test-page.component.scss']
})
export class TestPageComponent implements OnInit, OnDestroy {
constructor() { }
ngOnInit(): void {
}
destroy = new Subject();
ngOnDestroy(): void {
this.destroy.next(null);
}
goback() {
history.go(-1);
interval(100)
.pipe(takeUntil(this.destroy))
.subscribe(data => {
// 没有上一页则不会触发页面销毁,超时后关闭页面
(window as any).javaobj?.close();
});
}
}