Search code examples
javascriptangularhtmlangular-routingbrowser-history

History push state redirects instead of just pushing new state to browser history


I am trying to push a new state to browser history on my APP initialization but while pushing the state it also redirects the page which is not required.

Here is a demo working app. https://angular-tet5fy.stackblitz.io/page2?fbclid=IwAR1zP_UTnCQxKMp8o3ZXf-n4NR3ftu_4JoulLqItaONa-_wSPJ_DT95OgRU

This is the code:

ngAfterViewInit() {
    console.log('init called');
    var x = document.referrer;
    console.log('ref', x);

    if (x) {
      console.log('pushing state');
      this.location.pushState({id:'page3'}, 'Page3', '/page3');
    }
}

Expected behavior:

  1. Clicking on the link takes the user to page2.
  2. While page2 is initialized it should push state '/page3' to the browser history.
  3. When the user clicks the browser back now it should take to /page3 as it is was pushed to history in step2 above.

Current Behaviour:

  1. Clicking on the link, takes me to page2 but it automatically redirects to /page3 while pushing state.
  2. When clicked browser back, it takes me back to /page2.

Solution

  • ngAfterViewInit() {
        console.log('init called');
        var x = document.referrer;
        console.log('ref', x);
    
        if (x) {
          console.log('pushing state');
          let locat = location.href;
          history.replaceState({id:'page3'},'Page3','/page3');
          history.pushState(null,null,locat);
        }
    }
    

    What we do here it's change the url to the url you want to be the back with history.replaceState({id:'page3'},'Page3','/page3'); and then make a new entry in the history with history.pushState(null, null,locat); witht he first url.

    I answered you this question already in two different posts with only a little variation:

    Angular platformLocation pushState not working

    Angular: take user to home on clicking browser back button

    Live example fork: https://angular-stack-55624908.stackblitz.io/page2