Skip to content

Instantly share code, notes, and snippets.

@findelallc
Last active January 15, 2022 13:08
Show Gist options
  • Save findelallc/60c8b15969e002daa4787a4823d34b24 to your computer and use it in GitHub Desktop.
Save findelallc/60c8b15969e002daa4787a4823d34b24 to your computer and use it in GitHub Desktop.
// pure vanilla JS, no jQuery
let totalCount = 0, limitCount = 3;
tabSwitch();
function tabSwitch() {
if(localStorage.getItem('total_count')) {
totalCount = parseInt(atob(localStorage.getItem('total_count')));
if(totalCount >= limitCount) {
checkValidation();
}
}
document.addEventListener("visibilitychange", event => {
if (document.visibilityState == "visible") {
totalCount += 1;
document.getElementById("counter").innerText = totalCount;
localStorage.setItem('total_count', btoa(totalCount));
setTimeout(() => { checkValidation(); }, 500);
} else {
// leaaving the origin tab - tab goes inactive
}
});
}
function checkValidation() {
if(totalCount < limitCount) {
alert("you have "+ (limitCount-totalCount) + " tab switch limit left.");
}
else if(totalCount === limitCount) {
alert("Remember, you have reached max tab switching limit!");
}
else if(totalCount > limitCount) {
alert("Aborting exam...go to hell!");
//resetting
localStorage.removeItem('total_count');
totalCount = 0;
document.getElementById("counter").innerText = totalCount;
location.href = "https://imerit.net";
}
}
document.getElementById("counter").innerText = totalCount;
---------------------------------------------------------------------------------------------------------
// html part
<!DOCTYPE html>
<html>
<head>
<title>Tab Switcher Checker</title>
</head>
<body>
<p>You looked to the other tab(s): <b id="counter"></b> times</p>
<script src="script.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment