JavaScript History 对象
JavaScript Window History
Section titled “JavaScript Window History”window.history 对象提供对浏览器会话历史记录(session history)的访问,允许用户在当前会话中访问过的页面之间来回导航。
Window History 对象
Section titled “Window History 对象”window.history 对象可以直接作为 history 访问(因为 window 是浏览器中的全局对象)。
出于隐私原因,JavaScript 无法直接访问历史记录列表中的 URL。但是,它可以实现在历史记录中导航。
主要方法:
history.back(): 加载会话历史记录中的上一个 URL。与点击浏览器“后退”按钮相同。history.forward(): 加载会话历史记录中的下一个 URL。与点击浏览器“前进”按钮相同。history.go(delta): 从会话历史记录中加载特定 URL。例如,history.go(-1)等同于history.back(),history.go(1)等同于history.forward(),history.go(0)重新加载当前页面。
history.length 属性返回会话历史记录列表中的 URL 数量。
向后导航 (history.back())
Section titled “向后导航 (history.back())”history.back() 方法加载历史记录列表中的上一个 URL。
<!-- HTML --><!-- <button id="backButton">后退</button> -->
<script> const backButton = document.getElementById('backButton'); if (backButton) { backButton.addEventListener('click', function() { window.history.back(); }); }</script>
<!-- 要测试此功能,你需要从其他页面导航到此页面。 -->向前导航 (history.forward())
Section titled “向前导航 (history.forward())”history.forward() 方法加载历史记录列表中的下一个 URL。
<!-- HTML --><!-- <button id="forwardButton">前进</button> -->
<script> const forwardButton = document.getElementById('forwardButton'); if (forwardButton) { forwardButton.addEventListener('click', function() { window.history.forward(); }); }</script>
<!-- 要测试此功能,你需要从一个页面后退,然后使用此按钮。 -->导航到特定位置 (history.go())
Section titled “导航到特定位置 (history.go())”history.go(delta) 方法允许导航到历史记录中的一个相对位置。
<!-- HTML --><!-- <button id="goTwoBack">后退两页</button> -->
<script> const goTwoBackButton = document.getElementById('goTwoBack'); if (goTwoBackButton) { goTwoBackButton.addEventListener('click', function() { window.history.go(-2); // 后退两页 }); }</script>注意:如果在指定偏移量 delta 位置没有页面(例如,试图后退超过历史记录允许的范围),导航可能不会发生,或者在不同浏览器中表现不同(例如,什么也不做)。