History push state redirects instead of just pushi

2020-03-30 03:28发布

问题:

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.

回答1:

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



回答2:

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.

Because what you did, your history state goes: p1 -> p2 -> p3. That's in your description! You want it like this:

  1. Clicking on the link first push state p3
  2. Then take user to p2, and don't push state when initialized
  3. Browser back now works as expected

Edit:

This is how you can implement it. In page2.component.ts.

ngOnInit() {
  history.replaceState({ data: 'at page 3' }, 'Page3', '/page3');
  history.pushState({ data: 'at page 2' }, 'Page2', '/page2');
}

But again, read the doc.