如果用户在我的角度平台中,当用户点击浏览器的后退按钮时,我想将用户带到主页。
还有一个边缘案例要处理,如果用户通过谷歌搜索,Fb或直接输入链接来到我们的平台,那么我们不能这种行为,但如果他已经在我们的平台漫游,那么我们不想要每个后退按钮将用户带回家。
即
演示:点击下面的链接,然后点击谷歌搜索的第一个链接,然后尝试点击浏览器返回按钮,你会看到它带你到主页。
我尝试使用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。
您可以使用history.pushState(null, null, 'https://twitter.com/hello');
并将第三个参数作为应用程序的主页链接传递。在这种情况下,按回会将用户移动到主页。
看看这里; window.history API
或者:css-tricks
他们在那个页面做了什么有点棘手。诀窍是使用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