reCAPTCHA защищает интернет-пользователей от спама, где бы они ни находились. В данной статье мы создадим CaptchaField, который вы можете установить например в форму логина для защиты от ботов.
Чтобы начать работу, вам нужно будет зарегистрировать свой сайт на этой странице. Зарегистрируйте URL-адрес своего сайта и получите ключ. Добавьте следующий код в заголовок вашего файла index.html.
<header>
...
...
<sript src="https://www.google.com/recaptcha/api.js?onload=recaptchaOnload&render=explicit" async defer></script>
<script type="text/javascript">
function recaptchaOnload() {
Ext.GlobalEvents.fireEvent('GreCaptchaLoad');
}
</script>
...
...
</header>
Поле создает следующие события:
- RecaptchaInValid
- RecaptchaValid
- RecaptchaExpired
- RecaptchaErrorCallback
Ext.define('CaptchaField', {
extend: 'Ext.form.field.Base',
alias: 'widget.captchafield',
fieldSubTpl: [
'<div id="{captchaId}" class="{gRecaptcha}" data-sitekey="{dataSiteKey}"></div>'
],
isCaptchaValid: false,
initComponent: function() {
Ext.GlobalEvents.on('GreCaptchaLoad', this.renderGCaptcha, this);
this.callParent()
},
getSubTplData: function(fieldData) {
fieldData.dataSiteKey = this.dataSiteKey;
fieldData.gRecaptcha = 'g-recaptcha';
fieldData.captchaId = this.getGCaptchaDivId();
return fieldData;
},
getGCaptchaDivId: function() {
return this.getId() + '-greCaptchaDiv';
},
renderGCaptcha: function() {
var me = this;
grecaptcha.render(this.getGCaptchaDivId(), {
'sitekey' : this.dataSiteKey,
'callback' : function(response) {me.verifyCallback.call(me, response)},
'expired-callback': function() {me.onRecaptchaExpired.call(me)},
'error-callback': function() {me.onErrorCallback.call(me)},
'theme' : 'dark'
});
},
verifyCallback: function(response) {
this.isCaptchaValid = (response.length > 0);
this.fireEvent('validitychange', this, this.isCaptchaValid);
if(this.isCaptchaValid) {
this.fireEvent('RecaptchaInValid', this);
} else {
this.fireEvent('RecaptchaValid', this);
}
},
onRecaptchaExpired: function() {
console.log('onRecaptchaExpired');
this.isCaptchaValid = false;
this.fireEvent('validitychange', this, this.isCaptchaValid);
this.fireEvent('RecaptchaExpired', this);
},
onErrorCallback: function() {
this.isCaptchaValid = false;
this.fireEvent('validitychange', this, this.isCaptchaValid);
this.fireEvent('RecaptchaErrorCallback', this);
},
isValid : function() {
var me = this;
return me.disabled || this.isCaptchaValid;
},
});
Fiddle: