【问题标题】:Angular: take user to home on clicking browser back button [duplicate]Angular:单击浏览器后退按钮将用户带回家[重复]
【发布时间】:2019-04-03 09:16:17
【问题描述】:

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

还有一个边缘情况需要处理, 如果用户通过 google 搜索、Fb 或直接输入链接来到我们的平台,那么我们不能这样做,但如果他已经在我们的平台上漫游,那么我们不希望每个返回按钮将用户带回家。

  1. 用户输入链接并按下按钮 => 带他回家。

  2. 用户输入链接,现在点击按钮或链接,应用状态已更改,现在用户点击浏览器返回按钮 => 将用户带回上一页(正常行为)

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

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. 单击链接将用户带到第 2 页。 2. 初始化 page2 时,它应该将状态“/page3”推送到浏览器历史记录。 3. 当用户现在点击浏览器时,它应该转到/page3,因为它在上面的步骤2中被推送到历史记录。

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

【问题讨论】:

    标签: javascript angular routing angular2-routing browser-history


    【解决方案1】:

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

    看这里; window.history API

    或者:css-tricks

    【讨论】:

    • 它确实添加了一个新状态,但点击后退浏览器按钮除了从历史记录中删除状态之外什么也没做
    • 你想发布一些代码来看看你的实现吗?这绝对是正确的做法,如果您在底部看到第二个链接,则有一个带有代码的示例。
    • window.history.pushState(null, 'home', 'home');我什至试过这个 window.history.pushState(null, 'home', 'localhost:4200/home');
    • @mac-w 您能否查看页面底部的演示链接。因此,它不仅仅是推送状态,而是在推送历史记录时重定向到该状态。
    【解决方案2】:

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

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

      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

    【讨论】:

      猜你喜欢
      • 2011-09-15
      • 2022-01-21
      • 2010-12-19
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2016-12-25
      • 1970-01-01
      相关资源
      最近更新 更多