0👍
The idleness of this plugin will break when you do any activity as the mouse moves, keys down, mouse down, and touches start. So as the popup will close when you try to move the mouse.
Reversing the logic can help here.
For example, do not open the popup when the idle time reaches but open it when the user makes any activity after an inactive period.
In another word, do not open the popup instantly after idle time expires but open it when the user comes after long inactivity. In that way, the popup will be visible always and the user will come to know that he has been idle for so long, and now he can make a choice to log out or continue the session.
idle-vue
library has two hooks, onIdle
and onActive
. You can use onActive
hook to open the popup.
onActive() {
// Open the dialog when the user becomes active after an inactive period.
this.idle_dialog = true;
},
Now, you can allow users to choose options from that dialog whether to log out or to continue.
0👍
Using VueUse’s useIdle (with Swal alerts – but can be done with other components). The alert shows up a few minutes before logging you out so you have time to react;
<script setup lang="ts">
import Swal from "sweetalert2";
import { useIdle, useTimestamp, watchThrottled } from "@vueuse/core";
...
const EXTEND_MESSAGE_TIME = 60 * 13; //13 minutes
const IDLE_TIMEOUT = 60 * 15; //15 minutes
const now = useTimestamp();
const { idle, lastActive } = useIdle(IDLE_TIMEOUT);
const authStore = useAuthStore();
const router = useRouter();
const idleAlertShowing = ref<boolean>(false);
let idleTimePassed, idleTimeLeft;
const idledFor = computed(() => {
return Math.floor((now.value - lastActive.value) / 1000);
});
const formatTime = (time: number) => {
const minutes = Math.floor(time / 60);
const seconds = time - minutes * 60;
return `${minutes > 0 ? `${minutes} minutes and ` : ""}${seconds} second${
seconds > 1 ? "s" : ""
}`;
};
...
watchThrottled(
idledFor,
(newValue) => {
if (newValue === EXTEND_MESSAGE_TIME) {
Swal.fire({
html: `You have been inactive for <span id='swal-idle-time-passed'>${formatTime(
newValue
)}</span> and you will be timed out in <span id='swal-idle-time-left'>${formatTime(
IDLE_TIMEOUT - newValue
)}</span>.`,
showCancelButton: false,
showConfirmButton: false
});
idleAlertShowing.value = true;
idleTimePassed = document.querySelector("#swal-idle-time-passed");
idleTimeLeft = document.querySelector("#swal-idle-time-left");
} else if (newValue >= IDLE_TIMEOUT) {
authStore.logout();
router.push({ name: "sign-in" });
if (Swal.isVisible()) {
idleAlertShowing.value = false;
Swal.close();
}
} else if (newValue > EXTEND_MESSAGE_TIME && idle.value === true) {
if (idleTimePassed && idleTimeLeft) {
idleTimePassed.innerText = formatTime(newValue);
idleTimeLeft.innerText = formatTime(IDLE_TIMEOUT - newValue);
}
} else if (newValue <= 0) {
if (idleAlertShowing.value === true && Swal.isVisible()) {
Swal.close();
}
}
},
{ throttle: 500 }
);