diff --git a/js/recaptcha.js b/js/recaptcha.js index e69de29..4009cce 100644 --- a/js/recaptcha.js +++ b/js/recaptcha.js @@ -0,0 +1,30 @@ +/** + * @file + * Contains the definition of the behaviour recaptcha. + */ + +(function ($, Drupal, drupalSettings) { + Drupal.behaviors.recaptcha = { + attach: function (context, settings) { + $('.g-recaptcha', context).each(function () { + if (typeof grecaptcha === 'undefined') { + return; + } + if ($(this).hasClass('recaptcha-processed')) { + grecaptcha.reset(); + } + else { + grecaptcha.render(this, $(this).data()); + $(this).addClass('recaptcha-processed'); + } + }); + } + }; + + window.drupalRecaptchaOnload = function () { + $('.g-recaptcha').each(function () { + grecaptcha.render(this, $(this).data()); + $(this).addClass('recaptcha-processed'); + }); + } +})(jQuery, Drupal, drupalSettings); \ No newline at end of file diff --git a/recaptcha.libraries.yml b/recaptcha.libraries.yml index e69de29..4f77839 100644 --- a/recaptcha.libraries.yml +++ b/recaptcha.libraries.yml @@ -0,0 +1,6 @@ +recaptcha: + js: + js/recaptcha.js: {} + dependencies: + - core/drupal + - core/jquery \ No newline at end of file diff --git a/recaptcha.module b/recaptcha.module index 674fa36..3d40ea4 100644 --- a/recaptcha.module +++ b/recaptcha.module @@ -109,18 +109,9 @@ function recaptcha_captcha($op, $captcha_type = '') { '#markup' => '', '#suffix' => $noscript, '#attached' => [ - 'html_head' => [ - [ - [ - '#tag' => 'script', - '#attributes' => [ - 'src' => Url::fromUri('https://www.google.com/recaptcha/api.js', ['query' => ['hl' => \Drupal::service('language_manager')->getCurrentLanguage()->getId()], 'absolute' => TRUE])->toString(), - 'async' => TRUE, - 'defer' => TRUE, - ], - ], - 'recaptcha_api', - ], + 'library' => [ + 'recaptcha/google.recaptcha_' . \Drupal::service('language_manager')->getCurrentLanguage()->getId(), + 'recaptcha/recaptcha', ], ], ]; @@ -188,3 +179,32 @@ function template_preprocess_recaptcha_widget_noscript(&$variables) { $variables['language'] = $variables['widget']['language']; $variables['url'] = Url::fromUri('https://www.google.com/recaptcha/api/fallback', ['query' => ['k' => $variables['widget']['sitekey'], 'hl' => $variables['widget']['language']], 'absolute' => TRUE])->toString(); } + +/** + * Implements hook_library_info_build(). + */ +function recaptcha_library_info_build() { + $libraries = []; + $languages = \Drupal::service('language_manager')->getLanguages(); + foreach ($languages as $key => $language) { + $url = Url::fromUri('https://www.google.com/recaptcha/api.js', [ + 'query' => ['hl' => $key], + 'absolute' => TRUE, + ])->toString(); + $libraries["google.recaptcha_$key"] = [ + 'version' => '1.x', + 'header' => TRUE, + 'js' => [ + $url => [ + 'type' => 'external', + 'minified' => TRUE, + 'attributes' => [ + 'defer' => "defer", + 'async' => "async", + ], + ], + ], + ]; + } + return $libraries; +}