我试图在一个有角度的网站上实现Recaptcha V2。
我使用角度翻译,我不知道如何使用$scope
提供的正确语言重新生成reCaptcha对象
有什么方法吗?或使用正确的lang重新加载对象的过程?
谢谢
答案 0 :(得分:1)
根据API的限制,您可以动态加载脚本:
(source)
function loadScript(url, callback)
{
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
//modification so we can remove this after
return script;
}
注意:这是一个常规的JS函数
$scope.loadGoogleRecaptcha = function (id, lang) {
/// using timeout not to use $apply
$timeout(function () {
//set default value
var elemntID = id || false;
var language = lang || 'en';
if (!elemntID) {
console.warn('NO Id selected for re-captcha loading!')
return false;
}
var element = document.getElementById(elemntID)
if (angular.element(element).length == 0) {
console.warn('provided id doesn\'t exist ', elemntID);
return false;
}
//Delete oldscript
if ($rootScope.addedScript)
angular.element($rootScope.addedScript).remove();
//clear current recaptcha container
angular.element(element).empty();
var url = "https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=" + lang;
return $window.loadScript(url, function () {
console.log('Scipt loaded:', url);
})
});
}
使用angular-translate-localStorage 使用当前语言初始化验证码
$rootScope.addedScript = $scope.loadGoogleRecaptcha('g-recaptcha-register' ,$window.localStorage.getItem( 'NG_TRANSLATE_LANG_KEY'));
切换语言的功能样本
$rootScope.changeLanguage = function (langKey) {
$translate.use(langKey);
$rootScope.selectedLanguage = langKey;
$scope.loadGoogleRecaptcha('g-recaptcha-register' , langKey);
};
或者你可以使用观察者
$scope.$watch(
'selectedLanguage', function (n, o) {
//putting if to prevent double fetch the first time
if (!!n && n != o){
$rootScope.addedScript = $scope.loadGoogleRecaptcha('g-recaptcha-register', n);
}
}
);
答案 1 :(得分:0)
使用正确的hl属性更改recapacha src对我有用
继承我使用JQuery的解决方案
// reload capcha on translation
$rootScope.$on('$translateChangeSuccess', (event, data) => {
// reload captcha
let language;
if (data.language === 'en_CA') {
language = 'en';
} else {
language = 'fr';
}
const captchaElm = angular.element(document).find('.vc-recaptcha').find('iframe');
if (captchaElm.length) {
let src = captchaElm.attr('src');
src = src.replace(/(hl=)[^\&]+/, `$1${language}`);
captchaElm.attr('src', src);
}
});