Angular中离开应用时清除Token及校验跳转目标的实现方法
解决方案
beforeunload 事件本身无法直接获取跳转的目标URL,所以得换个思路:通过监听页面内的链接点击事件,提前判断用户是否要跳转到外部网站,再在beforeunload里根据这个标记决定是否清除Token。
具体实现步骤:
- 在组件内新增变量标记是否为外部跳转
- 监听页面点击事件,识别点击的链接是否属于外部域名
- 在
beforeunload方法中,仅当标记为外部跳转时清除Token - 组件销毁时移除所有监听事件
修改后的完整代码:
export class AppComponent implements OnInit, OnDestroy{ // 新增:标记是否为外部跳转 private isExternalNavigation = false; constructor( private overlayService: OverlayService, private logger: LoggerService, private userService: UserService, private oAuthStorage: OAuthStorage ) {} ngOnInit() { window.addEventListener('beforeunload', this.handleBeforeUnload); // 新增:监听页面点击事件 document.addEventListener('click', this.handleLinkClick); } // 新增:处理链接点击,判断是否为外部链接 handleLinkClick = (event: MouseEvent) => { const target = event.target as HTMLElement; // 找到点击的a标签 const link = target.closest('a'); if (link && link.href) { const url = new URL(link.href); // 对比当前页面域名和链接域名 this.isExternalNavigation = url.hostname !== window.location.hostname; } else { // 非a标签点击,重置标记 this.isExternalNavigation = false; } } handleBeforeUnload = () => { // 仅当是外部跳转时清除Token if (this.isExternalNavigation) { this.oAuthStorage.removeItem("access_token"); this.oAuthStorage.removeItem("refresh_token"); this.oAuthStorage.removeItem("id_token"); } } closeOverlay() { this.overlayService.closeOverlayByUrl(); } isLoggedIn() { return this.userService.isLoggedIn(); } ngOnDestroy() { window.removeEventListener('beforeunload', this.handleBeforeUnload); // 新增:移除点击事件监听 document.removeEventListener('click', this.handleLinkClick); } }
补充说明
- 该方案主要处理通过点击
<a>标签跳转外部网站的场景;对于JS代码触发的外部跳转(比如window.location.href、window.open),需要在执行跳转的代码里手动设置isExternalNavigation = true - Angular内部路由跳转不会触发
beforeunload事件(单页应用页面不会卸载),所以无需担心误清除Token
内容的提问来源于stack exchange,提问作者der papa
相关产品推荐
相关产品推荐

