javascript 自动刷新令牌和自动注销

wljmcqd8  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(157)

我是初学者网络开发人员。我在Laravel和Vue我的第一个项目。我需要做:

  1. 3分钟后自动注销-当用户处于非活动状态时
    1.自动ping我的令牌(domain.com/api/refresh)。
    我试着在我的main.js中的一个函数中这样做:
setTimeout(function() {
  window.location.href = "domain.com/logout";
}, 30000);

用于刷新,但它只运行一次-当我重新加载页面时。
我该怎么做?请帮帮我:)

j7dteeu8

j7dteeu81#

您可以使用以下事件mousemovemousedownkeypresstouchdown来确定用户是否处于活动状态。您将需要函数来启动计时器并将其重置。重置将用于上述事件。
在main.js中,执行以下操作:

const timeoutInMS = 180000; // 3 minutes -> 3 * 60 * 1000
let timeoutId;
  
function handleInactive() {
    // Here you want to logout a user and/or ping your token
}

function startTimer() { 
    // setTimeout returns an ID (can be used to start or clear a timer)
    timeoutId = setTimeout(handleInactive, timeoutInMS);
}

function resetTimer() { 
    clearTimeout(timeoutId);
    startTimer();
}
 
function setupTimers () {
    document.addEventListener("keypress", resetTimer, false);
    document.addEventListener("mousemove", resetTimer, false);
    document.addEventListener("mousedown", resetTimer, false);
    document.addEventListener("touchmove", resetTimer, false);
     
    startTimer();
}

然后在页面加载时调用setupTimers

**注意:**上述代码是检测用户是否处于非活动状态的一种方法。

相关问题