首頁  >  文章  >  web前端  >  如何使用 JavaScript 停止瀏覽器的後退按鈕?

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

王林
王林轉載
2023-09-07 14:21:021000瀏覽

如何使用 JavaScript 停止浏览器的后退按钮?

停止瀏覽器後退按鈕的意思是阻止使用者前往上一頁。有時,出於安全考慮,我們需要阻止使用者轉到目前頁面的後面。

例如,當您使用網路銀行從其網站進行某些交易時,大多數銀行網站不允許您返回。因為如果用戶從交易中間返回,可能會產生一些問題。因此,它只允許您完成交易或取消交易並重新開始。

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

使用window.history.forward()方法

window.history.forward() 方法允許我們將使用者重新導向到先前的 URL。視窗物件以堆疊格式儲存位置物件。因此,歷史物件的forward()方法找到最後一個位置並將使用者重新導向到該位置物件的URL。

文法

使用者可以依照下列語法使用歷史物件的forward()方法。

window.history.forward(); 

在上面的語法中,window指的是全域對象,每個網頁都包含window對象。

範例 1

在下面的範例中,我們使用 HTML 3499910bf9dac5ae3c52d5ede7383485 標籤建立了鏈接,將使用者傳送到 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://www.tutorialspoint.com/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://www.tutorialspoint.com/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 6c04bd5ca3fcae76e30b72ad730ca86d 元素中並呼叫 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://www.tutorialspoint.com/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() 方法。

以上是如何使用 JavaScript 停止瀏覽器的後退按鈕?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除