首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JavaScript 防止瀏覽器返回歷史頁面:location.replace 最佳實踐

     編輯:程式設計疑難解答

問題場景

登出連結 <a href="../Login.aspx">退出</a> 點擊後,使用者可透過瀏覽器「返回」鈕回到已登入頁面,造成安全隱患。

核心解法:location.replace() 替換歷史記錄

<a href="Login.aspx" id="logoutLink">退出</a>

<script>
document.getElementById('logoutLink').addEventListener('click', function(e) {
    e.preventDefault(); // 阻止預設跳轉
    // replace 不會在歷史堆疊新增記錄,返回鍵無法回來
    document.location.replace(this.href);
});
</script>

完整頁面範例

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Top.aspx.cs" Inherits="Admin_Top" %>
<!DOCTYPE html>
<html>
<head>
    <link href="../css/style_new.css" rel="stylesheet" />
    <script src="../js/jquery.js"></script>
    <script>
        $(function() {
            // 導航切換
            $(".nav li a").click(function() {
                $(".nav li a.selected").removeClass("selected");
                $(this).addClass("selected");
            });
            
            // 登出防返回
            $('a[href*="Login.aspx"]').click(function(e) {
                e.preventDefault();
                document.location.replace(this.href);
            });
        });
    </script>
</head>
<body style="background:url(../images/topbg.gif) repeat-x;">
    <form id="form1" runat="server">
        <div class="topleft">
            <a href="main.html" target="_parent"><img src="../images/loginlogo.png" title="系統首頁" /></a>
        </div>
        <div class="topright">
            <ul>
                <li><a href="#"><asp:Label ID="Label1" runat="server"></asp:Label></a></li>
                <li><a href="../Login.aspx" target="_parent">退出</a></li>
            </ul>
        </div>
    </form>
</body>
</html>

替代方案比較

方法原理優點缺點
location.replace(url)替換當前歷史記錄簡單、無歷史殘留無法適用於表單 POST
history.pushState(null, '', url) + onpopstate操作 History API可控制性強需處理 popstate 事件
登入頁檢查 Session 重導伺服器端驗證根治、最安全需後端配合
window.open(url, '_self')當前視窗開啟行為類似 replace可能被攔截器攔截

最佳安全實踐:前後端結合

// 前端:登出呼叫 API 並導向
fetch('/api/logout', { method: 'POST', credentials: 'include' })
    .then(() => location.replace('/login'));

// 後端:登入頁/受保護頁檢查
// Spring Security / Filter / Interceptor
if (session.getAttribute("user") == null) {
    response.sendRedirect("/login");
    return;
}

注意事項

  • replace 只影響當前標籤頁歷史,新分頁/視窗不受影響
  • 若登出前有多步操作,歷史堆疊仍保留更早頁面
  • 敏感系統建議:後端 Session 驗證為主,前端攔截為輔
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved