Angular:点击浏览器后退按钮将用户带回家[复制]

问题描述 投票:0回答:2

如果用户在我的角度平台中,当用户点击浏览器的后退按钮时,我想将用户带到主页。

还有一个边缘案例要处理,如果用户通过谷歌搜索,Fb或直接输入链接来到我们的平台,那么我们不能这种行为,但如果他已经在我们的平台漫游,那么我们不想要每个后退按钮将用户带回家。

  1. 用户输入链接并按按钮=>带他回家。
  2. 用户输入链接,然后单击按钮或链接,应用程序状态更改,现在用户单击浏览器返回按钮=>将用户返回到previos页面(正常行为)

演示:点击下面的链接,然后点击谷歌搜索的第一个链接,然后尝试点击浏览器返回按钮,你会看到它带你到主页。

https://www.google.com/search?ei=EnmkXJmYCIGLvQTinL_ICw&q=gap+men+shirts+ae&oq=gap+men+shirts+ae&gs_l=psy-ab.3...6313.6796..6983...0.0..0.141.399.0j3......0....1..gws-wiz.......0i71j0i22i30j0i22i10i30.To9hLinHj7I

我尝试使用pushState()实现它

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

    console.log(this.angLocation.path());

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

点击下面的链接,看看它在行动https://angular-tet5fy.stackblitz.io/page2?fbclid=IwAR1zP_UTnCQxKMp8o3ZXf-n4NR3ftu_4JoulLqItaONa-_wSPJ_DT95OgRU

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

当前行为:1。单击链接,将我带到page2,但在按下状态时它会自动重定向到/ page3。 2.当点击浏览器后,它会将我带回/ page2。

javascript angular routing angular2-routing browser-history
2个回答
0
投票

您可以使用history.pushState(null, null, 'https://twitter.com/hello');并将第三个参数作为应用程序的主页链接传递。在这种情况下,按回会将用户移动到主页。

看看这里; window.history API

或者:css-tricks


0
投票

他们在那个页面做了什么有点棘手。诀窍是使用history.pushState创建新的历史记录,然后订阅该位置的pop事件以将网页更改为主页。

我建议做一些有点不同和简单的事情,代码只需要这样一行:

  let locat = location.href;
    if (!!window.location.pathname && window.location.pathname !== '/') {
        history.replaceState(null,null,location.origin);
        history.pushState(null, null,locat);
    }

我们在这里做的是用history.replaceState(null,null,location.origin);改变你想要的家的网址,然后用history.pushState(null, null,locat);和他的第一个网址在历史上创造一个新的条目。

这里的例子:

https://stackblitz.com/edit/angular-stack-home-redirect-history?file=src/app/app.component.ts

试试这里:https://angular-stack-home-redirect-history.stackblitz.io/bye

© www.soinside.com 2019 - 2024. All rights reserved.