Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Allowing multiple forms to be recaptcha'ed with Amasty Invisible Google ReCaptcha for Magento 2
<?php
/**
* @author Amasty Team
* @copyright Copyright (c) 2017 Amasty (https://www.amasty.com)
* @package Amasty_InvisibleCaptcha
*/
?>
<?php
/**
*
* @see \Amasty\InvisibleCaptcha\Block\Captcha
* @var \Amasty\InvisibleCaptcha\Block\Captcha $block
*/
?>
<?php if ($block->isModuleOn()) : ?>
<script type="text/javascript">
require(['jquery'], function ($) {
formsToProtect = <?php echo $block->getCaptchaSelectorsJson() ?>;
formsToProtect.forEach(function(item) {
formToProtect = $(item)[0];
if (formToProtect) {
if (!window.formsToProtectOnPage || window.formsToProtectOnPage.constructor !== Array) {
window.formsToProtectOnPage = Array();
}
window.formsToProtectOnPage.push(formToProtect);
return;
}
});
if (window.formsToProtectOnPage) {
var recaptchaScript = document.createElement('script');
recaptchaScript.src = 'https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit';
recaptchaScript.attributes = 'async defer';
document.body.appendChild(recaptchaScript);
}
});
var onSubmit = function (formId, token) {
if (window.validationForInvisibleCaptchaForm[formId].valid()){
document.getElementById('amasty_invisible_token_' + formId).setAttribute('value', token);
document.getElementById('amasty_invisible_token_' + formId).form.submit();
} else {
grecaptcha.reset(window.grewidgets[formId]);
}
};
var onloadCallback = function () {
// Loop over forms
window.formsToProtectOnPage.forEach(function(formToProtect) {
// Get unique ID
var formId = formToProtect.id;
// Add invisible token to form
formToProtect.innerHTML +=
'<input type="hidden" id="amasty_invisible_token_' + formId + '" name="amasty_invisible_token" value=""/>';
require(['jquery', 'mage/mage'], function ($) {
if (!window.validationForInvisibleCaptchaForm || window.validationForInvisibleCaptchaForm.constructor !== Array) {
window.validationForInvisibleCaptchaForm = Array();
}
window.validationForInvisibleCaptchaForm[formId] = $('#' + formId);
});
// Create form-specific callback
if (!window.callBacks || window.callBacks.constructor !== Array) {
window.callBacks = Array();
}
window.callBacks[formId] = function(token){
onSubmit(formId,token);
};
// Render recaptcha for form
var widgetId = grecaptcha.render(formToProtect.querySelector("[type='submit']"), {
'sitekey': '<?php echo $block->getSiteKey(); ?>',
'callback': window.callBacks[formId]
});
if (!window.grewidgets || window.grewidgets.constructor !== Array) {
window.grewidgets = Array();
}
window.grewidgets[formId] = widgetId;
});
};
</script>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment