頁面載入時根據登入狀態動態顯示/隱藏按鈕,並處理 Session 過期跳轉登入頁後仍能正確隱藏。
<!-- HTML:預設隱藏,避免閃爍 -->
<input type="button" id="btnAction" value="操作" style="display: none;" />
<script>
// 後端模板引擎注入登入狀態 (JSP/Thymeleaf/Razor 等)
var isLogined = '<%= session.getAttribute("user") != null %>'; // "true" 或 "false"
if (isLogined === 'true') {
document.getElementById('btnAction').style.display = '';
}
</script>
function checkLoginStatus() {
fetch('/api/auth/status', { credentials: 'include' })
.then(res => res.json())
.then(data => {
const btn = document.getElementById('btnAction');
if (data.loggedIn) {
btn.style.display = '';
} else {
btn.style.display = 'none';
// 可選:導向登入頁
// window.location.href = '/login?redirect=' + encodeURIComponent(location.href);
}
});
}
// 頁面載入檢查
checkLoginStatus();
// 定期檢查 (每 5 分鐘)
setInterval(checkLoginStatus, 5 * 60 * 1000);
// 監聽 visibilitychange (頁面切回前台時檢查)
document.addEventListener('visibilitychange', () => {
if (!document.hidden) checkLoginStatus();
});
// Spring Boot
@GetMapping("/api/auth/status")
public Map<String, Object> authStatus(HttpSession session) {
return Map.of("loggedIn", session.getAttribute("user") != null);
}
| 錯誤做法 | 問題 | 正確做法 |
|---|---|---|
| JS 直接讀 Cookie 判斷 | HttpOnly Cookie 無法讀取;偽造風險 | 呼叫後端 API 驗證 Session |
| 前端單獨維護登入狀態 | 多標籤頁狀態不同步 | 統一向後端查詢 |
| 按鈕預設顯示,JS 隱藏 | 載入瞬間閃爍 (FOUC) | CSS 預設 display:none,JS 顯示 |
// Vue 3 Composition API
const isLoggedIn = ref(false);
const checkAuth = async () => {
const res = await fetch('/api/auth/status');
isLoggedIn.value = (await res.json()).loggedIn;
};
onMounted(() => { checkAuth(); setInterval(checkAuth, 300000); });
// 模板
<button v-if="isLoggedIn" @click="doAction">操作</button>