【问题标题】:Browser Back Button default behavior still executing on stop propigation浏览器后退按钮默认行为在停止传播时仍在执行
【发布时间】:2020-09-15 23:17:33
【问题描述】:

我有一个角站点,我在其中插入了一些代码,以使浏览器后退按钮的行为方式与后退 UI 按钮相同。但是,当我按回浏览器时,最后访问的页面会在默认行为执行之前闪烁一秒钟。

这是一个视频来说明我的意思 - 最后我展示了单击 UI 按钮的操作,这是我想要模拟的: Browser Back Button Demo

这是我在 Angular 中使用的代码:

@HostListener('window:popstate', ['$event'])
  onBrowserBackBtnClose(event: Event) {
      // Stop default behavior of the back button
      event.stopPropagation();
      event.preventDefault();
      // If we can go back...
      if (this.canGoBack) {
        // Load the previous question
        this.questionService.previousQuestion().subscribe(res => {
          // Activate the question route in place of the previous page
          this.router.navigate(['question'], {replaceUrl: true});
        });
      }
  }

我的理解是 event.stopPropagation(); 和 event.preventDefault(); 停止了这种闪烁行为?或者还有什么我不理解或遗漏的?

【问题讨论】:

  • 不是看window:popstate',而是看'window:beforeunload'呢?
  • 活动window:popstate 是不可取消的,所以你总是会看到最后一页。

标签: angular typescript


【解决方案1】:

如果我是你,我宁愿在这里使用原生 Angular 方法。在这种特殊情况下,您可以实现 CanDeactivate 或 CanActivate Route Guards。

在这两个接口中,方法都使用异步返回,例如:

可观察 |承诺 |布尔值 |网址树

【讨论】:

    【解决方案2】:

    您无法在浏览器中取消 popstate 事件,请在MDN page 上阅读有关该事件的更多信息。话虽如此,您可以更新窗口历史记录(技术上是 hack)并再次推送当前位置,以便该页面将导航回当前页面,使用:

    window.history.pushState(null, null, window.location.pathname);

    不确定如何将其应用到您的代码中,因为我没有您的应用程序的工作演示,但它可能看起来像:

    @HostListener('window:popstate', ['$event'])
    onBrowserBackBtnClose(event: Event) {
      // prevent browser from moving to different page
      window.history.pushState(null, null, window.location.pathname);
          
      // If we can go back...
      if (this.canGoBack) {
        // Load the previous question
        this.questionService.previousQuestion().subscribe(res => {
          // Activate the question route in place of the previous page
          this.router.navigate(['question'], {
            replaceUrl: true
          }); // you will need some other code to determine and navigate to next page if user chooses to
        });
      }
    }

    【讨论】:

    • 关闭但我仍然得到最后一页的闪烁
    • @webdevelopwolf 你能分享一下 stackblitz 应用程序的问题吗?
    • @WebDevelopWolf 你能分享更多细节吗?
    猜你喜欢
    • 2010-12-13
    • 1970-01-01
    • 2016-05-23
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    相关资源
    最近更新 更多