History API
History API 通过全局对象 history 提供对浏览器会话历史记录的访问(请勿与 WebExtensions history 混淆)。它公开了有用的方法和属性,让您可以来回浏览用户的历史记录,并操作历史堆栈的内容。
概念与用法
前进和后退
向后浏览历史记录
js
history.back();
此操作与用户点击浏览器工具栏上的 后退 按钮的操作完全相同。
同样,您可以像这样前进(相当于用户点击 前进 按钮):
js
history.forward();
移动到历史记录中的特定位置
您可以使用 go() 方法从会话历史记录加载特定页面,该页面通过其相对于当前页面的位置来标识。(当前页面的相对位置为 0。)
向后移动一页(等同于调用 back())
js
history.go(-1);
向前移动一页,就像调用 forward() 一样
js
history.go(1);
类似地,您可以通过传递 2 来前进 2 页,依此类推。
go() 方法的另一个用途是通过传递 0 或不带参数调用来刷新当前页面。
js
// The following statements
// both have the effect of
// refreshing the page
history.go(0);
history.go();
通过查看 length 属性的值,您可以确定历史堆栈中的页面数量。
js
const numberOfEntries = history.length;
接口
History-
允许操作浏览器会话历史记录(即,当前页面加载的选项卡或框架中访问过的页面)。
PopStateEvent-
popstate事件的接口。
示例
以下示例为 popstate 事件分配一个监听器。然后,它说明了 history 对象的一些方法,用于在当前选项卡的浏览器历史记录中添加、替换和移动。
js
window.addEventListener("popstate", (event) => {
alert(
`location: ${document.location}, state: ${JSON.stringify(event.state)}`,
);
});
history.pushState({ page: 1 }, "title 1", "?page=1");
history.pushState({ page: 2 }, "title 2", "?page=2");
history.replaceState({ page: 3 }, "title 3", "?page=3");
history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // alerts "location: http://example.com/example.html, state: null"
history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3}"
规范
| 规范 |
|---|
| HTML # the-history-interface |
浏览器兼容性
加载中…