Change ReCaptcha language OnClick

2019-07-23 00:40发布

I realize that it is trivial to change the Recaptcha language by adding the "hl" option to api.js.

https://www.google.com/recaptcha/api.js?hl=fr

What I would like to do is change the Recaptcha language when someone clicks on a language picker which is exposed via a QueryString parameter such as "?lang=fr" I have js that will parse the parameter but I cannot seem to reload the script in the head tag to include the param.

I've looked at all the conditional IF...ELSE javascript loading articles. Is there any way to load Recaptcha options with version 2?

2条回答
劳资没心,怎么记你
2楼-- · 2019-07-23 00:52

Simple solution

You can do it like this:

HTML

<div id="captcha_container"></div>
<select id="ddllanguageListsGoogleCaptcha"></select>
<input id="btnApplyLanguage" type="button" value="Apply Selected Language" />

JS

// Button for updating captcha language
$('#btnApplyLanguage').click(function () {
    updateGoogleCaptchaLanguage($('#ddllanguageListsGoogleCaptcha').val());
});

// Update language captcha 
function updateGoogleCaptchaLanguage(selectedLanguage) {

    // Get GoogleCaptcha iframe
    var iframeGoogleCaptcha = $('#captcha_container').find('iframe');

    // Get language code from iframe
    var language = iframeGoogleCaptcha.attr("src").match(/hl=(.*?)&/).pop();

    // Get selected language code from drop down
    var selectedLanguage = $('#ddllanguageListsGoogleCaptcha').val();

    // Check if language code of element is not equal by selected language, we need to set new language code
    if (language !== selectedLanguage) {
        // For setting new language 
        iframeGoogleCaptcha.attr("src", iframeGoogleCaptcha.attr("src").replace(/hl=(.*?)&/, 'hl=' + selectedLanguage + '&'));
    }
}

Online demo (jsFiddle)

查看更多
甜甜的少女心
3楼-- · 2019-07-23 01:06

I do not think it is possible to do set recaptcha language through javascript directly at the moment. As you stated, it is however possible using the parameter 'hl' during script loading.

If you need to change the language of your application dynamically without reloading the page, you can do this by removing the recaptcha script link from the head section and instead, loading it directly with a call from javascript. When your user changes the language by clicking a button, you can now reload recaptcha with the new language by calling the load function again.

In my case the recaptcha element is shown inside a modal, the user response is sent to the server over ajax and is validated on the server side against Google. Something like this does the trick:

/* Clears recaptcha HTML element of all content, clears 
 * recaptcha element id so that the code would know to create 
 * the new HTML. Reloads recaptcha code with the new specified 
 * language using jQuery */
var captchaReload = function(langCode) {
    $('#recaptchaDiv').empty();
    recaptchaElement = null;
    var url = "https://www.google.com/recaptcha/api.js?render=explicit&hl=" + langCode;
    $.getScript(url);
};

/* Called by recaptcha when the user solves the puzzle.
 * The incoming parameter 'response' is generated by the recaptcha 
 * and needs to be validated against google separately, which 
 * is not shown here */
var captchaValidate = function(response){
    console.log('Doing captcha response: ' + response);
    grecaptcha.reset();
    $('#captchaModal').modal('hide');
    // TODO: Add server side call for validating the client response
};

/* Variable for keeping track if recaptcha has already been created */
var recaptchaElement = null;

/* Called for initializing the recaptcha element and opening the modal */
var captchaShow = function () {
    // Initialize recaptcha if it is not present yet
    if(recaptchaElement === null){
        recaptchaElement = grecaptcha.render('recaptchaDiv', {
            'sitekey'   : 'YoUrReCaPtChAsItEkEy',
            'theme'     : 'light',
            'callback'  : captchaValidate
        });
    }
    // Open captcha modal
    window.setTimeout(function() {
        $('#captchaModal').modal('show');
    },300);
};

Now, at page load or when the user selects a new language, you can do:

captchaReload('fr');

And it should remove the existing recaptcha object from the page and reload one in the correct language. After that you can open the modal using:

captchaShow();
查看更多
登录 后发表回答