From 1eaa0f7631e29534d73b3ac1a07b6c530b4ad8d8 Mon Sep 17 00:00:00 2001 From: Zankaria Date: Sun, 4 Aug 2024 01:29:34 +0200 Subject: [PATCH] main.js: abstract captcha renderer --- templates/main.js | 65 ++++++++++++++++++++++++++--------------------- 1 file changed, 36 insertions(+), 29 deletions(-) diff --git a/templates/main.js b/templates/main.js index 938320dd..9bebf755 100755 --- a/templates/main.js +++ b/templates/main.js @@ -239,22 +239,7 @@ function getCookie(cookie_name) { } {% endraw %} -{% if config.dynamic_captcha %} -function isDynamicCaptchaEnabled() { - let cookie = getCookie('captcha-required'); - return cookie === '1'; -} - -function getCaptchaPubKey() { -{% if config.recaptcha %} - return "{{ config.recaptcha_public }}"; -{% elseif config.turnstile %} - return "{{ config.turnstile_public }}"; -{% else %} - return null; -{% endif %} -} - +{% if config.turnstile %} // Wrapper function to be called from thread.html window.onCaptchaLoadTurnstile_post_reply = function() { onCaptchaLoadTurnstile('post-reply'); @@ -267,26 +252,48 @@ window.onCaptchaLoadTurnstile_post_thread = function() { // Should be called by the captcha API when it's ready. Ugly I know... D: function onCaptchaLoadTurnstile(action) { - let pub_key = getCaptchaPubKey(); - if (!pub_key) { - console.error("Missing public captcha key!"); - return; - } + let renderer = { + renderOn: function(container) { + let widgetId = turnstile.render(container, { + sitekey: "{{ config.turnstile_public }}", + action: action, + }); + if (widgetId === undefined) { + console.error('Could not render Turnstile captcha!'); + return undefined; + } + document.addEventListener('post', function(e) { + // User posted! Reset the captcha. + turnstile.reset(widgetId); + }); + return widgetId; + }, + remove: function(widgetId) { + turnstile.remove(widgetId); + } + }; - let widgetId = turnstile.render('captcha-container', { - sitekey: pub_key, - action: action, - }); - if (widgetId === undefined) { - console.error('Could not render Turnstile captcha!'); - return; + onCaptchaLoad(renderer); +} +{% endif %} + +function onCaptchaLoad(renderer) { + let widgetId = renderer.renderOn('#captcha-container'); + if (widgetId === null) { + console.error('Could not render captcha!'); } document.addEventListener('post', function(e) { // User posted! Reset the captcha. - turnstile.reset(widgetId); + renderer.reset(widgetId); }); } +{% if config.dynamic_captcha %} +function isDynamicCaptchaEnabled() { + let cookie = getCookie('captcha-required'); + return cookie === '1'; +} + function initDynamicCaptcha() { if (isDynamicCaptchaEnabled()) { let captcha_hook = document.getElementById('captcha');