/* * dynamic-comment-form.js -- Captcha challenge loader * Copyright © 2022 Jakob L. Kreuze * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see * . */ function makeRequest (method, url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.onload = function () { if (xhr.status >= 200 && xhr.status < 300) { resolve(xhr.response); } else { reject({ status: xhr.status, statusText: xhr.statusText }); } }; xhr.onerror = function () { reject({ status: xhr.status, statusText: xhr.statusText }); }; xhr.send(); }); } window.addEventListener("load", () => { let primaryDisplay = document.getElementById("comment-form-primary"); primaryDisplay.removeAttribute("hidden"); let altDisplay = document.getElementById("comment-form-alt"); altDisplay.remove(); let trigger = document.getElementById("captcha-challenge-trigger"); let triggerBlock = document.getElementById("captcha-trigger-block"); trigger.addEventListener("click", (event) => { let captchaField = document.getElementById("comment-captcha"); let captchaId = document.getElementById("captcha-id"); let captchaImage = document.getElementById("captcha-image"); trigger.innerHTML = "Please wait..."; trigger.disabled = true; if (captchaId.value === "") { makeRequest("GET", "/api/challenge/captcha") .then(function (data) { // Update form with parsed values. let challengeData = JSON.parse(data); captchaId.value = challengeData["challenge-id"]; captchaImage.src = challengeData["image"]; // Unhide fieldset. captchaField.removeAttribute("hidden"); // Hide initial trigger. triggerBlock.remove(); }) .catch(console.err); } event.preventDefault(); }); });