angular8 设置禁止返回处理

场景:禁止浏览器点击返回键做后退,以及鼠标or触摸板做后退的情况。

大多数网上提供的解决方案都是 👇 但这不适用于单页面应用程序

    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', function () {
      history.pushState(null, null, document.URL);
    });

实现:路由监听,导航结束的时候调用window.history.pushState方法,仅改变网址,网页不会跳转,也不会获取到新的内容,本质上网页还停留在原页面从而实现禁止返回键。

 this.router.events.subscribe((event: any) => {
      if (event instanceof NavigationEnd) {
        history.pushState(null, null, document.URL);
      }
});

 


此随笔乃本人学习工作记录,如有疑问欢迎在下面评论,转载请标明出处。

如果对您有帮助请动动鼠标右下方给我来个赞,您的支持是我最大的动力

posted @ 2020-04-27 11:23  huangenai  阅读(1091)  评论(0编辑  收藏  举报