停止瀏覽器后退按鈕的含義是阻止用戶轉(zhuǎn)到上一頁。有時,出于安全考慮,我們需要阻止用戶轉(zhuǎn)到當前頁面的后面。
例如,當您使用網(wǎng)上銀行從其網(wǎng)站進行某些交易時,大多數(shù)銀行網(wǎng)站不允許您返回。因為如果用戶從交易中間返回,可能會產(chǎn)生一些問題。因此,它只允許您完成交易或取消交易并重新開始。
在這里,我們將學習使用 JavaScript 防止用戶從當前網(wǎng)頁返回上一個網(wǎng)頁的各種方法。在本教程中,我們將學習使用 JavaScript 或 jQuery 停止瀏覽器后退按鈕。
使用window.history.forward()方法
window.history.forward() 方法允許我們將用戶重定向到之前的 URL。窗口對象以堆棧格式存儲位置對象。因此,歷史對象的forward()方法找到最后一個位置并將用戶重定向到該位置對象的URL。
語法
用戶可以按照以下語法使用歷史對象的forward()方法。
window.history.forward();
登錄后復制
在上面的語法中,window指的是全局對象,每個網(wǎng)頁都包含window對象。
示例 1
在下面的示例中,我們使用 HTML <a> 標簽創(chuàng)建了鏈接,將用戶發(fā)送到 TutorialsPoint 網(wǎng)站的主頁。在 JavaScript 中,我們剛剛添加了 window.history.forward() 方法。
現(xiàn)在,每當用戶從當前網(wǎng)頁轉(zhuǎn)到tutorialsPoint網(wǎng)站的主頁時,他們將無法返回該頁面。
<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 > tutorialspoint</a> <script> window.history.forward(); </script> </body> </html>
登錄后復制
示例 2
在下面的示例中,我們使用 setTimeOut() 函數(shù)在特定時間后將用戶重定向到上一頁。在setTimeOut()函數(shù)中,我們在1秒后調(diào)用window.history.forward()方法。
因此,在輸出中,用戶可以觀察到,每當他們從TutorialsPoint網(wǎng)站的主頁返回當前頁面時,它都會在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 > 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> 元素中并調(diào)用 stopBack() 函數(shù)。
示例 3
在下面的示例中,我們使用 window.history.go() 方法將用戶重定向到上一頁。每當網(wǎng)頁加載時,它就會調(diào)用 stopBack 函數(shù),它將用戶從當前頁面重定向到上一頁,這樣我們就可以停止瀏覽器的后退按鈕。
<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 > tutorialspoint</a> <div id = "output"> </div> <script> var output = document.getElementById('output'); function stopBack() { window.history.go(1); } </script> </body> </html>
登錄后復制
我們學會了如何阻止用戶返回特定網(wǎng)頁。我們使用了 window.history.forward() 和 window.history.go() 方法。
以上就是如何使用 JavaScript 停止瀏覽器的后退按鈕?的詳細內(nèi)容,更多請關(guān)注www.92cms.cn其它相關(guān)文章!