Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browser Back Button default behavior still executing on stop propigation

I have an angular site in which I've inserted some code to make the browser back button behave in the same way as the back UI button. However when I press back on the browser I get the last visited page flashing for a second before the default behavior executes.

Here's a video to show what I mean - at the end I show the what clicking the UI button does which is what I want to emulate: Browser Back Button Demo

And here's the code I'm using in 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});
        });
      }
  }

My understanding was that event.stopPropagation(); and event.preventDefault(); stopped this flickering behavior? Or is there something else I'm not understanding or missing?

like image 270
Web Develop Wolf Avatar asked Nov 07 '22 05:11

Web Develop Wolf


1 Answers

If I was you I would rather use native Angular approach here. In this particular case you can implement CanDeactivate or CanActivate Route Guards.

In both of this interfaces methods uses asynchronous returns such as:

Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree

like image 187
Timothy Avatar answered Nov 15 '22 11:11

Timothy