1

Im building an Angular application and having some troubles with closing the menu on popstate. when the side menu is open and the user clicked on the back button on his mobile device i want the menu to close the menu, for that im using pop state like that

@HostListener('window:popstate', ['$event'])
  onPopState(event) {
    if (this.isMenuOpened) {
      this.toggleSidebar();
    }
      return ;
  }

The problem Im having is that the back action also works, so the menu is close but the back action is also happens. i cant use history.go(1) because it makes the page load again and i don't want this kind of behaviour.

did you have any ideas ?

Matan Shushan
  • 1,204
  • 1
  • 10
  • 25

2 Answers2

0

Popstate is not cancellable as per the specs. However, you can try to do this

@HostListener('window:popstate', ['$event'])
onPopState(event) {
    if (this.isMenuOpened) {
        event.preventDefault();
        history.go(1); // re-changes the url to what it should be
        this.toggleSidebar();
    }
    return ;
}
michaelz
  • 56
  • 6
  • there is a problem with that solution because ```history.go(1);``` make the page render again and i don't want it to happen – Matan Shushan Jan 29 '19 at 11:03
0

try this -

 $(window).on( "popstate", function(event){
          if( !event.originalEvent.state ){
          history.pushState( "nohb", null, "" );
          return;
          }
      });

Instead of history.go(1) use window.history.forward()

window.history.forward() this function in the first page uses the history of the browser and forces it to navigate forward instead of going to the previous page. Therefore, every time the user clicks the back button, it will result in the Browser navigating or pushing the user forward and showing the same page.

Sneha Pawar
  • 1,097
  • 6
  • 14