如何使用JavaScript阻止瀏覽器的後退按鈕?


阻止瀏覽器的後退按鈕意味著阻止使用者返回上一頁。有時,出於安全考慮,我們需要阻止使用者返回當前頁面。

例如,大多數銀行網站在您使用網上銀行進行交易時不允許您後退。因為如果使用者在交易中途返回,可能會產生一些問題。因此,它只允許您完成交易或取消交易並重新開始。

在這裡,我們將學習使用JavaScript阻止使用者從當前網頁返回上一網頁的各種方法。在本教程中,我們將學習如何使用JavaScript或jQuery阻止瀏覽器後退按鈕。

使用window.history.forward()方法

window.history.forward()方法允許我們將使用者重定向到上一個URL。window物件以棧的形式儲存location物件。因此,history物件的forward()方法查詢最後一個位置並將使用者重定向到該location物件的URL。

語法

使用者可以按照以下語法使用history物件的forward()方法。

window.history.forward(); 

在上文的語法中,window指的是全域性物件,每個網頁都包含window物件。

示例1

在下面的示例中,我們建立了一個連結,使用HTML <a>標籤將使用者傳送到TutorialsPoint網站的主頁。在JavaScript中,我們只是添加了window.history.forward()方法。

現在,無論何時使用者從當前網頁訪問TutorialsPoint網站的主頁,他們都將無法返回此頁面。

<html>
<body> 
   <h2>Preventing the browser's back button using the <i> window.history.forward() </i> method. </h2>
   <h3>Click the below link. </h3>
   <a href = "https://tutorialspoint.tw/index.htm"> tutorialspoint</a>
   <script>
      window.history.forward();
   </script>
</body>
</html>

示例2

在下面的示例中,我們使用了setTimeOut()函式,在特定時間後將使用者重定向到上一頁。在setTimeOut()函式中,我們在1秒後呼叫window.history.forward()方法。

因此,在輸出中,使用者可以觀察到,無論何時他們從TutorialsPoint網站的主頁返回當前頁面,它都將在1秒後再次重定向。

<html>
<body>
   <h2>Preventing the browser's back button using the <i> window.history.forward() </i> method. </h2>
   <h3>Click the below link. </h3>
   <a href = "https://tutorialspoint.tw/index.htm"> tutorialspoint </a> 
   <script>
      setTimeout(() => { window.history.forward() }, 1000);
   </script>
</body>
</html>

使用window.history.go()方法

window.history.go()方法將使用者重定向到上一個位置的URL。

語法

使用者可以按照以下語法使用window.history.go()方法來阻止瀏覽器的後退按鈕。

<body onload = "stopBack();"></body>
<script>
   function stopBack() {
      window.history.go(1);
   }
</script> 

在上文的語法中,我們將onload屬性新增到HTML <body>元素並呼叫stopBack()函式。

示例3

在下面的示例中,我們使用了window.history.go()方法將使用者重定向到上一頁。每當網頁載入時,它將呼叫stopBack函式,並將使用者從當前頁面重定向到上一頁,透過這種方式,我們可以阻止瀏覽器的後退按鈕。

<html>
<body onload="stopBack();">
   <h2>Preventing the browser's back button using the <i>window.history.go() </i> method.</h2>
   <h3>Click the below link. </h3>
   <a href = "https://tutorialspoint.tw/index.htm"> tutorialspoint</a>
   <div id = "output"> </div>
   <script>
      var output = document.getElementById('output');
      function stopBack() {
         window.history.go(1);
      }
   </script>
</body>
</html>

我們學習瞭如何阻止使用者返回特定網頁。我們使用了window.history.forward()和window.history.go()方法。

更新於:2023年2月16日

14K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.