You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JSON Web Token过期时自动登出用户?解决页面刷新定时器失效问题

解决页面刷新后保留自动登出定时器的方案

核心思路

把token的绝对过期时间戳存在本地存储(localStorage/sessionStorage),页面加载时读取该时间戳,计算剩余过期时间后重新设置定时器;同时处理页面后台暂停定时器的问题,确保过期时能触发登出。

具体实现步骤

  1. 登录时存储过期时间戳
    登录成功后,计算token的绝对过期时间(当前时间+过期时长),存在localStorage中,同时初始化定时器:
function signIn() {
  // 假设登录成功后获取到过期时长expiryTime(单位:毫秒)
  const expiryTime = 3600000; // 示例:1小时有效期
  const expireAt = Date.now() + expiryTime;
  
  // 存储绝对过期时间戳
  localStorage.setItem('authExpireAt', expireAt.toString());
  
  // 初始化登出定时器
  window.authTimerId = setTimeout(logout, expiryTime);
}
  1. 页面加载时重新初始化定时器
    页面刷新或首次加载时,读取存储的过期时间,判断是否已过期,未过期则设置剩余时间的定时器:
function initAuthTimer() {
  const expireAtStr = localStorage.getItem('authExpireAt');
  if (!expireAtStr) return;

  const expireAt = parseInt(expireAtStr, 10);
  const now = Date.now();
  const remainingTime = expireAt - now;

  // 已过期直接登出
  if (remainingTime <= 0) {
    logout();
    localStorage.removeItem('authExpireAt');
    return;
  }

  // 设置剩余时间的定时器
  window.authTimerId = setTimeout(() => {
    logout();
    localStorage.removeItem('authExpireAt');
  }, remainingTime);
}

// 页面加载时触发
window.addEventListener('load', initAuthTimer);
  1. 处理页面后台暂停定时器的问题
    浏览器会暂停后台页面的定时器,导致登出时间不准,因此监听页面可见性变化,重新校验过期时间:
document.addEventListener('visibilitychange', () => {
  // 页面重新可见时,重新初始化定时器
  if (!document.hidden) {
    clearTimeout(window.authTimerId);
    initAuthTimer();
  }
});
  1. 登出时清理资源
    登出时清除本地存储的过期时间和定时器:
function logout() {
  // 执行你的登出逻辑:清除token、跳转登录页等
  localStorage.removeItem('authExpireAt');
  clearTimeout(window.authTimerId);
  
  // 示例:跳转到登录页
  window.location.href = '/login';
}

注意事项

  • 用localStorage存储的话,关闭浏览器后数据会保留;如果希望关闭浏览器就失效,改用sessionStorage。
  • 绝对时间戳比剩余时间更可靠,避免页面刷新时计算误差。
  • 若用户手动修改本地存储的过期时间,可能导致逻辑失效,可结合后端接口在关键操作时校验token有效性作为兜底。

内容的提问来源于stack exchange,提问作者abduljalil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 01:15:36