JavaScript - 歷史物件



視窗歷史物件

在 JavaScript 中,視窗“history”物件包含有關瀏覽器會話歷史的資訊。它包含當前會話中訪問過的 URL 陣列。

“history”物件是“window”物件的屬性。history 屬性可以訪問或不訪問其所有者物件,即 window 物件。

使用“history”物件的方法,您可以轉到瀏覽器的會話的先前、後續或特定 URL。

歷史物件方法

視窗歷史物件提供了一些有用的方法,允許我們在歷史列表中前後導航。

按照以下語法在 JavaScript 中使用“history”物件。

window.history.methodName();
OR
history.methodName();

您可以使用“window”物件訪問“history”物件。

JavaScript 歷史 back() 方法

JavaScript history back() 方法載入歷史列表中的前一個 URL。

語法

按照以下語法使用 history back() 方法。

history.back();

示例

在以下程式碼的輸出中,您可以單擊“後退”按鈕以轉到前一個 URL。它充當瀏覽器的後退按鈕。

<html>
<body>
   <p> Click "Go Back" button to load previous URL </p>
   <button onclick="goback()"> Go Back </button>
   <p id = "output"> </p>
   <script>
      function goback() {
         history.back();
         document.getElementById("output").innerHTML +=
		 "You will have gone to previous URL if it exists";
      }
   </script>
</body>
</html>

JavaScript 歷史 forward() 方法

history 物件的 forward() 方法將帶您到下一個 URL。

語法

按照以下語法使用 forward() 方法。

history.forward();

示例

在以下程式碼中,單擊按鈕以轉到下一個 URL。它充當瀏覽器的向前按鈕。

<html>
<body>
   <p> Click "Go Forward" button to load next URL</p>    
   <button onclick = "goforward()"> Go Forward </button>
   <p id = "output"> </p>
   <script>
      function goforward() {
         history.forward();
         document.getElementById("output").innerHTML =
		 "You will have forwarded to next URL if it exists."
     }
   </script>
</body>
</html>

JavaScript 歷史 go() 方法

history 物件的 go() 方法將帶您到瀏覽器會話的特定 URL。

語法

按照以下語法使用 go() 方法。

history.go(count);

在上述語法中,“count”是一個數字值,表示您要訪問哪個頁面。

示例

在以下程式碼中,我們使用 go() 方法從當前網頁移動到前兩個頁面。

<html>
<body>
   <p> Click the below button to load 2nd previous URL</p>
   <button onclick = "moveTo()"> Move at 2nd previous URL </button>
   <p id = "output"> </p>
   <script>
      function moveTo() {
         history.go(-2);
         document.getElementById("output").innerHTML =
		 "You will have forwarded to 2nd previous URL if it exists.";
      }
   </script>
</body>
</html>

示例

在以下程式碼中,我們使用 go() 方法從當前網頁移動到前兩個頁面。

<html>
<body>
   <p> Click the below button to load 2nd next URL</p>    
   <button onclick = "moveTo()"> Move at 2nd next URL </button>
   <p id = "output"> </p>
   <script>
      function moveTo() {
         history.go(2);
         document.getElementById("output").innerHTML = 
		 "You will have forwarded to 2nd next URL if it exists.";
      }
  </script>
</body>
</html>

以下是完整的視窗歷史物件參考,包括屬性和方法:

歷史物件屬性列表

history 物件僅包含“length”屬性。

屬性 描述
length它返回物件的長度,表示物件中存在的 URL 數量。

歷史物件方法列表

history 物件包含以下 3 種方法。

方法 描述
back()它將帶您到前一個網頁。
forward()它將帶您到下一個網頁。
go()它可以帶您到特定網頁。
廣告