1
0
dwelling-home/web/assets/js/captcha_refresh.js

40 lines
1.5 KiB
JavaScript
Raw Normal View History

2023-02-05 00:54:18 +04:00
const g_captcha_timeout_seconds = 600;
const e_captcha = document.getElementsByClassName("captcha")[0];
let g_captcha_timeout_remain = g_captcha_timeout_seconds;
let g_current_captcha_id = e_captcha.children[0].value;
async function getNewCaptcha() {
const id = await fetch("/api/captcha/", { method: "POST"}).then(r => r.text());
g_current_captcha_id = e_captcha.children[0].value = id;
const style = window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark";
setTimeout(() => { e_captcha.children[1].src = `/api/captcha/${id}/image?style=${style}` }, 600);
g_captcha_timeout_remain = g_captcha_timeout_seconds;
}
e_captcha.children[3].innerHTML =
`<button id="refresh">Refresh</button>ed in <b><span id="remain">600</span></b> seconds.`;
const captcha_refresh = document.getElementById("refresh");
const captcha_remain = document.getElementById("remain");
captcha_refresh.classList.toggle("refresh");
captcha_refresh.addEventListener("click", async e => {
e.preventDefault();
e.target.disabled = true;
setTimeout(async () => {
e.target.disabled = false;
await fetch(`/api/captcha/${g_current_captcha_id}?remove`); }, 3000);
e_captcha.children[2].value = "";
await getNewCaptcha();
});
// Remove unused CAPTCHA on a server.
window.addEventListener("unload", () => fetch(`/api/captcha/${g_current_captcha_id}?remove`));
setInterval(async () => {
captcha_remain.innerText = --g_captcha_timeout_remain;
if (g_captcha_timeout_remain == 0)
await getNewCaptcha();
}, 1000);