历史推送状态重定向,而不仅仅是将新状态推送到浏览器历史记录 [英] History push state redirects instead of just pushing new state to browser history

查看:31
本文介绍了历史推送状态重定向,而不仅仅是将新状态推送到浏览器历史记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 APP 初始化时将新状态推送到浏览器历史记录,但在推送状态的同时,它还重定向了不需要的页面.

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.

这是一个演示工作应用程序.https://angulard-stack=https://angulard.page2IwAR1zP_UTnCQxKMp8o3ZXf-n4NR3ftu_4JoulLqItaONa-_wSPJ_DT95OgRU

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

这是代码:

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');
    }
}

预期行为:

  1. 点击链接会将用户带到第 2 页.
  2. 当 page2 被初始化时,它应该将状态 '/page3' 推送到浏览器历史记录中.
  3. 当用户现在点击浏览器时,它应该转到/page3,因为它在上面的第 2 步中被推送到历史记录中.

当前行为:

  1. 点击链接,我会转到 page2,但它在推送状态时会自动重定向到/page3.
  2. 当点击浏览器返回时,它会将我带回/page2.

推荐答案

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);
    }
}

我们在这里做的是将 url 更改为 你想成为后面的 url 使用 history.replaceState({id:'page3'},'Page3','/page3'); 然后用 history.pushState(null, null,locat); 和他的第一个 url 在历史记录中创建一个新条目.

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 不起作用

Angular:点击浏览器时将用户带回家返回按钮

分叉实例:https://angular-stack-55624908.stackblitz.io/page2

这篇关于历史推送状态重定向,而不仅仅是将新状态推送到浏览器历史记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆