實現一個登錄流程控制:用戶首次登錄時展示引導頁(A 頁),引導完成可跳轉主頁(B 頁);非首次登錄直接跳轉主頁,不再顯示引導頁。
需在客戶端記錄「是否首次登錄」狀態,常用方案對比:
| 方案 | 存儲位置 | 生命週期 | 適用場景 |
|---|---|---|---|
| Cookie | 瀏覽器 | 可設定過期時間(如 1 年) | 跨會話記憶,兼容性好 |
| sessionStorage | 瀏覽器標籤頁 | 標籤頁關閉即銷毀 | 單會話臨時狀態 |
| localStorage | 瀏覽器 | 永久,除非手動清除 | 長期記憶首選,容量 5MB |
| Session(服務端) | 服務器內存/Redis | 默認 30 分鐘無操作過期 | 敏感狀態、多端同步 |
// 登錄驗證通過後
function onLoginSuccess() {
// 標記已完成首次登錄
localStorage.setItem('hasVisited', 'true');
// 跳轉主頁
window.location.href = 'pageB.html';
}
<script>
// 必須在頁面渲染前執行,放在 <head> 中
(function() {
if (localStorage.getItem('hasVisited') === 'true') {
// 非首次訪問,直接重定向
window.location.replace('pageB.html'); // replace 避免歷史記錄回退
}
// 首次訪問,繼續加載當前頁面
})();
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>引導頁</title>
<script>
// 必須最先執行的攔截邏輯
(function() {
if (localStorage.getItem('hasVisited')) {
window.location.replace('main.html');
}
})();
</script>
</head>
<body>
<div class="guide-container">
<h1>歡迎使用</h1>
<button id="enterBtn">進入主頁</button>
</div>
<script>
document.getElementById('enterBtn').onclick = function() {
localStorage.setItem('hasVisited', 'true');
window.location.href = 'main.html';
};
</script>
</body>
</html>
localStorage.setItem('guideVersion', '2.1.0')。使用 localStorage 在頁面加載最早期攔截跳轉,是實現「首次引導、後續直達」最簡潔高效的前端方案。關鍵點:攔截腳本置於 <head> 首位,使用 replace 避免歷史堆疊。