Drupal 7 + ReCAPTCHA + Ajax
Today's problem - on an old site with Drupal 7, the recaptcha module does not work in the modal window for the web form.
This patch, which was found on Drupal org, is enough to solve this issue.
diff --git a/js/recaptcha.js b/js/recaptcha.js
new file mode 100644
index 0000000..058a1db
--- /dev/null
+++ b/js/recaptcha.js
@@ -0,0 +1,31 @@
+(function ($, window, Drupal) {
+
+ Drupal.behaviors.recaptcha = {
+ attach: function (context) {
+ $('.g-recaptcha', context).each(function() {
+ if (typeof grecaptcha === 'undefined' || typeof grecaptcha.render !== "function") {
+ return;
+ }
+ if ($(this).hasClass('recaptcha-processed')) {
+ grecaptcha.reset();
+ }
+ else {
+ if (!$(this).hasClass('recaptcha-processed')) {
+ grecaptcha.render(this, $(this).data());
+ $(this).addClass('recaptcha-processed');
+ }
+ }
+
+ });
+ }
+ };
+
+ window.drupalRecaptchaOnload = function() {
+ $('.g-recaptcha').each(function() {
+ if (!$(this).hasClass('recaptcha-processed')) {
+ grecaptcha.render(this, $(this).data());
+ $(this).addClass('recaptcha-processed');
+ }
+ });
+ }
+})(jQuery, window, Drupal);
diff --git a/recaptcha.module b/recaptcha.module
index 8beb8f8..49968ae 100644
--- a/recaptcha.module
+++ b/recaptcha.module
@@ -128,20 +128,21 @@ function recaptcha_captcha($op, $captcha_type = '') {
$captcha['form']['recaptcha_widget'] = array(
'#markup' => '<div' . drupal_attributes($attributes) . '></div>',
'#suffix' => $noscript,
- );
-
- // @todo: #1664602: D7 does not yet support "async" in drupal_add_js().
- // drupal_add_js(url('https://www.google.com/recaptcha/api.js', array('query' => array('hl' => $language->language), 'absolute' => TRUE)), array('defer' => TRUE, 'async' => TRUE, 'type' => 'external'));
- $data = array(
- '#tag' => 'script',
- '#value' => '',
- '#attributes' => array(
- 'src' => url($recaptcha_src, array('query' => array('hl' => $language->language), 'absolute' => TRUE)),
- 'async' => 'async',
- 'defer' => 'defer',
+ '#attached' => array(
+ 'js' => array(
+ drupal_get_path('module', 'recaptcha') . '/js/recaptcha.js',
+ array(
+ 'data' => url($recaptcha_src, array('query' => array('hl' => $language->language, 'render' => 'explicit', 'onload' => 'drupalRecaptchaOnload'), 'absolute' => TRUE)),
+ 'type' => 'external',
+ 'defer' => TRUE,
+ 'attributes' => array(
+ // This will only work once #1664602 is resolved in Drupal core.
+ 'async' => 'async',
+ ),
+ ),
+ ),
),
);
- drupal_add_html_head($data, 'recaptcha_api');
}
else {
// Fallback to Math captcha as reCAPTCHA is not configured.