场景需求:
如下图所示,用户可以在previousPage通过点击事件到达showcolor页面,showcolor页面有3个子页面,分别是red,green,yellow 页面。
为了记录用户的点击行为,在用户进入子页面的时候在url上加上hash值加以区分。
当用户点击浏览器的返回按钮时,可以正确的返回到前一页面,而不是在子页面之间层层返回。
实现方式:
1. 使用history.replaceState() 的方式
// url: https://test.bigtest.com/showcolor#Red
window.history.replaceState("", document.title, '#Red');
2. 使用history.pushState() 的方式
// url: https://test.bigtest.com/showcolor#Red
window.history.pushState("", document.title, '#Red');
3.使用window.location.hash的方式
// url: https://test.bigtest.com/showcolor#Red
window.location.hash ="#Red"
分析
这三种方式在展现hash方面的结果是一致的,但是对于浏览器的返回按钮被点击时的反应不同。
使用history.replaceState()的方式
replaceState() 是修改了当前的历史记录项,而不是新建一个。所以无论用户在showcolor页面多少次的点开不同的子颜色页面,当点击返回时,都会回到previousPage页面。
使用history.pushState() 的方式或window.location.hash的方式
pushState()是新建了History对象的记录,所以当在Red子页面点击返回按钮时,会先返回到showcolor页面,然后再次点击返回按钮才会返回到previousPage页面
Tip
如果想在color页面上通过刷新操作关闭子页面,显示color主页面,那么就需要在初始化color页面时,调用一次replaceState()函数。
因为通过replaceState()操作,可以清除子页面的hash值。代码如下:
// 初始化
init() {
window.history.replaceState("", document.title, window.location.pathname);
}