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

77 lines
2.1 KiB
JavaScript
Raw Normal View History

2022-09-12 22:07:08 +02:00
import Events from '../_events'
2024-04-26 17:06:32 +02:00
const CaptchaUI = ((window) => {
const NAME = 'js-captcha'
2022-09-12 22:07:08 +02:00
2024-04-26 17:06:32 +02:00
const init = () => {
console.log(`${NAME}: init`)
2022-09-12 22:07:08 +02:00
2024-04-26 17:06:32 +02:00
const submitListener = (e) => {
console.log(`${NAME}: Validating Captcha ...`)
const field = e.currentTarget.querySelectorAll(`.${NAME}, .g-recaptcha`).forEach((el) => {
grecaptcha.execute(el.dataset.widgetid)
})
}
2022-09-12 22:07:08 +02:00
2024-04-26 17:06:32 +02:00
const attachCaptcha = () => {
console.log(`${NAME}: Rendering Captcha ...`)
2022-09-12 22:07:08 +02:00
2024-04-26 17:06:32 +02:00
const fields = document.querySelectorAll(`.${NAME}, .g-recaptcha`)
const grecaptcha = window.grecaptcha
2023-10-10 20:03:01 +02:00
2024-04-26 17:06:32 +02:00
fields.forEach((el, i) => {
if (el.dataset.widgetid || el.innerHTML !== '') {
// already initialized
return
}
2022-09-12 22:07:08 +02:00
2024-04-26 17:06:32 +02:00
const form = el.closest(form)
const widgetid = grecaptcha.render(el, el.dataset)
el.dataset.widgetid = widgetid
2022-09-12 22:07:08 +02:00
2024-04-29 23:04:58 +02:00
if (el.dataset.size === 'invisible' && !el.dataset.callback) {
2024-04-26 17:06:32 +02:00
grecaptcha.execute(widgetid)
form.addEventListener('submit', submitListener)
}
2022-09-12 22:07:08 +02:00
2024-04-26 17:06:32 +02:00
el.classList.add(`${NAME}-active`)
el.dispatchEvent(new Event(`${NAME}-ready`))
})
2022-09-12 22:07:08 +02:00
}
2024-04-29 23:04:58 +02:00
window.noCaptchaFieldRender = attachCaptcha
const loadScript = () => {
if (document.getElementById('captchaAPI')) {
console.log(`${NAME}: Already loading API`)
return
2024-04-26 17:06:32 +02:00
}
2022-09-12 22:07:08 +02:00
2024-04-26 17:06:32 +02:00
console.log(`${NAME}: Loading Captcha API ...`)
2022-09-12 22:07:08 +02:00
2024-04-26 17:06:32 +02:00
const script = document.createElement('script');
script.id = 'captchaAPI';
2024-04-29 23:04:58 +02:00
script.src = `https://www.google.com/recaptcha/api.js?onload=noCaptchaFieldRender&render=explicit&hl=${document.querySelector('html').getAttribute('lang').substr(0, 2)}`
2024-04-26 17:06:32 +02:00
script.async = true
2022-09-12 22:07:08 +02:00
2024-04-26 17:06:32 +02:00
document.body.append(script)
}
2022-09-12 22:07:08 +02:00
2024-04-29 23:04:58 +02:00
if (document.querySelectorAll('.g-recaptcha').length) {
if (typeof window.grecaptcha !== 'undefined') {
attachCaptcha()
}
loadScript();
} else {
2024-04-26 17:06:32 +02:00
console.log(`${NAME}: No Captcha fields.`)
}
}
2022-09-12 22:07:08 +02:00
2024-04-26 17:06:32 +02:00
window.addEventListener(`${Events.LODEDANDREADY}`, init)
window.addEventListener(`${Events.AJAX}`, init)
})(window)
2022-09-12 22:07:08 +02:00
2024-04-26 17:06:32 +02:00
export default CaptchaUI