我正在使用HTML5历史记录API来在选择某些产品属性(例如绿色汽车,蓝色汽车)时修改URL,以便进行深度链接共享。
然而,这不是一个单页应用程序,因此我不想劫持用户的返回按钮:如果他们按下返回键,我希望允许他们返回到上一页,而不是上一个汽车颜色。
如何实现最佳效果?
历史记录示例:
/page1
/page2
/page2?color=green
/page2?color=red
/page2?color=blue
然后按浏览器的返回按钮回到
/page1
页面。我正在使用HTML5历史记录API来在选择某些产品属性(例如绿色汽车,蓝色汽车)时修改URL,以便进行深度链接共享。
然而,这不是一个单页应用程序,因此我不想劫持用户的返回按钮:如果他们按下返回键,我希望允许他们返回到上一页,而不是上一个汽车颜色。
如何实现最佳效果?
历史记录示例:
/page1
/page2
/page2?color=green
/page2?color=red
/page2?color=blue
/page1
页面。看起来我应该使用
history.replaceState();
与其使用history.pushState();
,不如使用history.replaceState()
。它替换了浏览器的URL,但不会添加到历史记录对象中,因此后退按钮可以按照我想要的方式工作。
history.replaceState()
与history.pushState()
完全相同,只是replaceState()修改当前历史记录条目而不是创建新条目。
JS
function getCurrentPath() {
return sessionStorage.getItem("currentPath");
}
function getPreviousPath() {
return sessionStorage.getItem("previousPath");
}
function setCurrentPath(path) {
var currentPath = getCurrentPath();
if (currentPath != path) {
sessionStorage.setItem("previousPath", currentPath);
sessionStorage.setItem("currentPath", path);
} else {
console.log('Path has not changed: ' + path);
}
}
function goToPrevious() {
var previousPath = getPreviousPath();
if (previousPath && previousPath != 'null') {
window.location.href = previousPath;
} else {
alert('Previous page is not defined.');
}
}
test1.html
<!DOCTYPE html>
<html>
<head>
<title>Test 1</title>
<meta charset="UTF-8">
<script src="test.js"></script>
<script>
setCurrentPath('test1.html');
console.log('Current Path:', getCurrentPath());
console.log('Previous Path:', getPreviousPath());
</script>
</head>
<body>
<button onclick="goToPrevious();">Go to previous page</button>
<a href="test2.html">Test 2</a>
<a href="?color=red">Red</a>
<a href="?color=green">Green</a>
<a href="?color=blue">Blue</a>
</body>
</html>
test2.html
<!DOCTYPE html>
<html>
<head>
<title>Test 2</title>
<meta charset="UTF-8">
<script src="test.js"></script>
<script>
setCurrentPath('test2.html');
console.log('Current Path:', getCurrentPath());
console.log('Previous Path:', getPreviousPath());
</script>
</head>
<body>
<button onclick="goToPrevious();">Go to previous page</button>
<a href="test1.html">Test 1</a>
<a href="?color=red">Red</a>
<a href="?color=green">Green</a>
<a href="?color=blue">Blue</a>
</body>
</html>