【问题标题】:Handle Back button with Angular [Chrome]使用 Angular [Chrome] 处理后退按钮
【发布时间】:2021-10-07 09:35:05
【问题描述】:

我正在使用 Angular 创建一个项目,在我的应用程序中我需要处理后退按钮事件。以下是除一种情况外运行良好的代码

代码:

this.location.subscribe(event => {
 //logout
});
history.pushState({}, '');

此代码仅在用户执行某些活动时有效,如果用户刚刚登陆页面并单击返回按钮,则不会捕获此事件。我尝试了所有方法,但都不起作用。

【问题讨论】:

  • 您需要处理后退按钮究竟是为了什么?如果您使用路由器作为主要事实来源,我发现您需要它的情况很少

标签: javascript angular google-chrome


【解决方案1】:

一个简单的方法是在用户每次单击返回按钮时添加popstate 事件。它将被解雇。

window.addEventListener('popstate', (event) => {
    // The popstate event is fired each time when the current history entry changes.

    // logout or do any thing you like

}, false);

如果这不起作用,您可以使用 Angular Router 并检查调用了哪个事件。

constructor(router: Router) {
    router.events
      .subscribe((event: NavigationStart) => {
        if (event.navigationTrigger === 'popstate') {
          // Perform actions
        }
      });
}

【讨论】:

  • 在没有任何活动的情况下直接单击后退按钮时不起作用
  • 你在哪里添加了这段代码?
  • 在 app.component.ts 文件中
  • 是的,尝试在ngOnInit() 中添加它,它应该可以工作。尝试在事件中添加控制台并检查控制台。添加和测试很简单,我只是做了它的工作。
  • 不,它不工作,只有当用户进行点击或任何活动时才起作用
【解决方案2】:

这解决了我的问题,即使用户没有活动也可以捕获

@HostListener('window:popstate', [$event])
onPopState(event: any) {
  console.log('Event', event);
}

PS:在 Chrome 中测试

【讨论】:

    【解决方案3】:

    您可以尝试像这样覆盖整个onpopstate

    window.onpopstate = function () {
      // Your logic should be here...
    }.bind(this); // This line is to bind the components
    

    【讨论】:

      【解决方案4】:

      我认为在用户与网页交互之前,beforeunload 被触发并且页面会在你捕捉到popstate 之前被卸载。结合在一起,它们似乎正在发挥作用。

      请注意,您将无法完全覆盖浏览器行为作为安全功能。

      https://angular-ivy-pbvgpj.stackblitz.io/

      export class AppComponent {
        name = 'Angular ' + VERSION.major;
        backButtonClicked = false;
      
        ngOnInit(): void {
          history.pushState(null, document.title, location.href);
        }
      
        @HostListener('window:popstate', ['$event']) onClickBack(
          event: PopStateEvent
        ) {
          history.pushState(null, document.title, location.href);
          this.backButtonClicked = true;
        }
      
        @HostListener('window:beforeunload', ['$event']) onBeforeUnload(
          event: BeforeUnloadEvent
        ) {
          history.pushState(null, document.title, location.href);
          this.backButtonClicked = true;
        }
      }
      

      Stackblitz

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多