Angular10登录后点击浏览器后退仍返回登录页 移动端适配问题问询
适配全端的登录后禁止后退到登录页实现方案
失效根因
原
window.history.forward()逻辑在移动端失效,是因为iOS Safari、安卓内置浏览器等移动端环境对历史栈操作的触发时机限制严格,Angular单页应用的路由跳转不会触发浏览器原生页面重载,导致这段逻辑无法被正确执行。
方案1:Angular路由守卫(符合框架规范,全端兼容)
该方案完全依托Angular自身路由逻辑实现,不需要操作原生浏览器API,适配性最高:
- 生成登录状态守卫
执行Angular CLI命令生成守卫文件:ng generate guard guards/auth - 编写守卫逻辑
import { Injectable } from '@angular/core'; import { CanActivate, Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private router: Router) {} canActivate(): boolean { if (localStorage.getItem('IsLogin') != null) { // 已登录状态访问登录页直接跳转至bookings首页 this.router.navigate(['/bookings']); return false; } return true; } } - 绑定守卫到登录路由
在项目路由配置文件中给登录页路由添加守卫校验:const routes: Routes = [ { path: 'login', component: LoginComponent, canActivate: [AuthGuard] }, { path: 'bookings', component: BookingsComponent }, // 其余路由配置 ];
方案2:替换历史栈记录(直接消除登录页历史条目,兼容性最好)
登录验证成功跳转时,替换当前历史栈中的登录页记录,让浏览器历史栈中完全不存在登录页的条目,用户点击后退自然无法回到登录页:
// 登录接口验证通过后的跳转逻辑 loginSuccessCallback() { localStorage.setItem('IsLogin', 'true'); // 用replaceUrl参数跳转,替换当前历史栈条目 this.router.navigate(['/bookings'], { replaceUrl: true }); }
两种方案配合使用即可覆盖所有桌面、移动端场景,无需再保留原window.history.forward()逻辑
内容的提问来源于stack exchange,提问作者farhad Khoja
相关产品推荐
相关产品推荐

