我不認爲現在可以通過javascript直接設置recaptcha語言。正如你所說的那樣,在腳本加載過程中可以使用參數'hl'。
如果您需要在不重新加載頁面的情況下動態更改應用程序的語言,可以通過從頭部刪除recaptcha腳本鏈接來完成此操作,而是直接使用javascript調用加載它。當用戶通過單擊按鈕更改語言時,您現在可以通過再次調用加載函數來使用新語言重新加載recaptcha。
在我的情況下,recaptcha元素顯示在模態內,用戶響應通過ajax發送到服務器,並在服務器端針對Google進行驗證。 像這樣的伎倆:
/* 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);
};
現在,在頁面加載或當用戶選擇一個新的語言,你可以這樣做:
captchaReload('fr');
它應該從刪除現有的reCAPTCHA對象頁面並用正確的語言重新加載一個。之後,你可以使用打開模式:
captchaShow();
您需要重新加載頁面或破壞HTML元素和腳本在一個新的,爲了做到。注意說明reCaptcha ID或reCaptcha容器必須爲空的錯誤。 – colecmc