Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular-recaptcha: Change language with site language change

I have website which uses three different languages switchable by user. Language switch is done on client side by JavaScript (AngularJS).

I am using reCAPTCHA 2 on my website and need to change language of reCAPTCHA when the user switches languge of website.

I know already that I can force the language by this code when the reCAPTCHA is initialized:

<script src="https://www.google.com/recaptcha/api.js?hl=cs"></script>

However, when you need reloading reCAPTCHA, you use this code and it doesn't take any parameter for custom language:

grecaptcha.reset();

Is it possible to do that without refreshing the page and re-initialization of reCAPTCHA widget with different language?

EDIT

I am using angular-recaptcha to render the widget. This means that:

  • I need calling vcRecaptchaApiLoaded callback after reCAPTCHA API init
  • I cannot change the code rendered by vcRecaptcha directive

This is code which renders reCAPTCHA widget:

<div
    vc-recaptcha
    key="'---- YOUR PUBLIC KEY GOES HERE ----'"
></div>

This is the code which insludes reCAPTCHA API into my web:

<script
  src="https://www.google.com/recaptcha/api.js?onload=vcRecaptchaApiLoaded&render=explicit&hl=cs"
  async defer
></script>
like image 414
Knut Holm Avatar asked Nov 01 '15 10:11

Knut Holm


1 Answers

You can simply empty the div.g-recaptcha and load the script again (programmaticaly).

The function below should do the trick:

function changeRecaptchaLanguage(language) {
  document.querySelector('.g-recaptcha').innerHTML = '';

  var script = document.createElement('script');
  script.src = 'https://www.google.com/recaptcha/api.js?hl=' + language;
  script.async = true;
  script.defer = true;
  document.querySelector('head').appendChild(script);
}

Take a look at the example in the snippet below:

function changeRecaptchaLanguage(language) {
  document.querySelector('.g-recaptcha').innerHTML = '';
  
  var script = document.createElement('script');
  script.src = 'https://www.google.com/recaptcha/api.js?hl=' + language;
  script.async = true;
  script.defer = true;
  document.querySelector('head').appendChild(script);
}

var curr = 'en';

changeRecaptchaLanguage(curr);

document.querySelector('button').addEventListener('click', function() {
  curr = curr === 'en' ? 'pt-BR' : 'en';
  changeRecaptchaLanguage(curr);
});
<div>Other stuff</div>
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
<button>Change language</button>
like image 77
Buzinas Avatar answered Oct 22 '22 14:10

Buzinas