webpack-bootstrap-ui-kit/src/js/ui/turnstile.js

72 lines
1.7 KiB
JavaScript
Raw Normal View History

2023-10-31 21:06:31 +01:00
import Events from '../_events'
2023-11-02 18:32:15 +01:00
2023-10-31 21:06:31 +01:00
const NAME = 'uiTurnstile'
2024-03-12 00:16:24 +01:00
const SELECTOR = `.${NAME},.js-turnstile`
2023-10-31 21:06:31 +01:00
const init = () => {
2024-03-12 00:16:24 +01:00
console.log(`${NAME}: init`)
2024-03-07 02:49:23 +01:00
const captchas = document.querySelectorAll(SELECTOR)
if (!captchas.length) {
2023-11-02 18:32:15 +01:00
console.log(`${NAME}: No Captcha fields.`)
return
}
2024-03-12 00:16:24 +01:00
if (!document.querySelector('#captchaAPI') && typeof window.turnstile === 'undefined') {
2023-11-02 18:32:15 +01:00
loadScript(init)
2023-10-31 21:06:31 +01:00
return
}
2024-03-12 00:16:24 +01:00
renderCaptcha()
}
const renderCaptcha = () => {
console.log(`${NAME}: renderCaptcha`)
const captchas = document.querySelectorAll(SELECTOR)
2024-03-07 02:49:23 +01:00
captchas.forEach((el) => {
2024-03-07 12:47:22 +01:00
if (el.dataset[NAME] || el.innerHTML.length > 0) {
2024-03-12 00:16:24 +01:00
if (el.dataset.widgetid) {
turnstile.reset(el.dataset.widgetid)
}
2024-03-07 12:47:22 +01:00
return
}
2024-03-12 00:16:24 +01:00
const widgetid = window.turnstile.render(el, {
sitekey: el.dataset.sitekey,
callback: function (token) {
console.log(`${NAME}: Challenge Success ${token}`);
},
})
const form = el.closest('form')
form.addEventListener('submit', () => {
console.log(`${NAME}: submit`)
window.turnstile.reset(el.dataset.widgetid)
})
el.dataset.widgetid = widgetid
2024-03-07 12:47:22 +01:00
el.dataset[NAME] = true
2024-03-07 02:49:23 +01:00
})
2023-11-02 18:32:15 +01:00
}
2024-03-12 00:16:24 +01:00
const loadScript = () => {
2023-11-02 18:32:15 +01:00
console.log(`${NAME}: Loading Captcha API ...`)
const script = document.createElement('script');
script.id = 'captchaAPI';
2024-03-12 00:16:24 +01:00
script.src = `https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=renderCaptcha&hl=${document.querySelector('html').getAttribute('lang').substr(0, 2)}`
2023-11-02 18:32:15 +01:00
script.async = true
document.body.append(script)
2023-10-31 21:06:31 +01:00
}
2024-03-12 00:16:24 +01:00
window.renderCaptcha = renderCaptcha
2023-10-31 21:06:31 +01:00
window.addEventListener(`${Events.LODEDANDREADY}`, init)
window.addEventListener(`${Events.AJAX}`, init)