页面载入时使用history.replaceState修改history记录
利用按钮1,2修改history记录;按钮3,4,5进行前进后退测试,在history细节中查看信息
点击按钮1后,将使用history.pushState加入一条history记录
点击按钮2后,将使用history.replaceState修改当前history记录
点击按钮3后,页面将后退到前一个history记录
点击按钮4后,页面将前进一个history记录
点击按钮5后,页面将后退两个history记录
根据history细节可以发现pushState和replaceState的区别
history细节
#history {
.btn {
font-size: torem(14px);
line-height: 1.5;
padding: 0 torem(10px);
}
}
/**
* 点击处理
*/
function handleHistory(e) {
const { trigger } = e.target.dataset;
if (trigger === 'push') {
window.history.pushState({ page: 2 }, '', '/history.html?pagetwo');
} else if (trigger === 'replace') {
window.history.replaceState({ page: 3 }, '', '/history.html?pagethree');
} else if (trigger === 'back') {
window.history.back();
} else if (trigger === 'forward') {
window.history.forward();
} else if (trigger === 'go') {
window.history.go(-2);
}
e.preventDefault();
e.stopPropagation();
}
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#history').addEventListener('click', handleHistory, false);
window.onpopstate = (e) => {
const li = document.createElement('li');
const info = `location: ${document.location}; state: ${JSON.stringify(e.state)}`;
const text = document.createTextNode(info);
li.appendChild(text);
document.querySelector('.detail').appendChild(li);
};
});
window.onload = () => {
window.history.replaceState({ page: 1 }, '', '/history.html?pageone');
};