- pushState
向浏览器会话历史堆栈中添加一个状态,并更新地址栏。 - onpopstate
当调用history.back(), history.go(), 点击浏览器回退前进按钮时触发。 - length
会话历史记录个数 - go
返回上一页:go(-1),下一页:go(1) - replaceState
修改当前记录实体 - 监听pushState
history.pushState = function () {
const result = history.pushState.apply(null, arguments);
history.onpushstate({});
return result;
};
history.onpushstate = window.onpopstate = function (event) {
console.log(
"location: " +
document.location +
", state: " +
JSON.stringify(event.state)
);
};
使用示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button onclick="addEntry()">add entry</button>
<button onclick="replaceEntry()">replace entry</button>
<button onclick="back()">back</button>
<button onclick="go()">go</button>
<script>
window.onpopstate = function (event) {
console.log(
"location: " +
document.location +
", state: " +
JSON.stringify(event.state)
);
};
function addEntry() {
history.pushState({ page: 1 }, "title 1", "?page=1");
history.pushState({ page: 2 }, "title 2", "?page=2");
}
function replaceEntry() {
history.replaceState({ page: 3 }, "title 3", "?page=3");
}
function back() {
history.back();
}
function go() {
history.go(1);
}
</script>
</body>
</html>
<!--
点击addEntry, history = [path,path?page=1,path?page=2]
点击replaceEntry, history = [path,path?page=1,path?page=3]
点击back, history = [path,path?page=1]
-->
使用案例1:
应用有iframe,iframe内嵌页面跳转,点击浏览器回退按钮,返回到 iframe 内嵌页面跳转前的页面。期望回退到父页面的上一个页面。
// 内嵌页面跳转不添加到浏览器会话history中
const iframe1 = document.getElementById('iframe1');
iframe1.contentWindow.history.pushState = iframe1.contentWindow.history.replaceState;