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

75 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-26 17:06:32 +02:00
if(el.dataset.size === 'invisible' && !el.dataset.callback){
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-26 17:06:32 +02:00
const loadScript = (callback) => {
if(typeof window.grecaptcha !== 'undefined'){
callback()
}
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';
script.src = `https://www.google.com/recaptcha/api.js?render=explicit&hl=${ document.querySelector('html').getAttribute('lang').substr(0,2)}`
script.async = true
script.onload = function() {
console.log(`${NAME}: Captcha API is loaded.`)
callback()
}
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-26 17:06:32 +02:00
if(document.querySelectorAll('.g-recaptcha').length){
loadScript(attachCaptcha);
}else{
console.log(`${NAME}: No Captcha fields.`)
}
2022-09-12 22:07:08 +02:00
2024-04-26 17:06:32 +02:00
window.noCaptchaFieldRender = attachCaptcha
}
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