在angular 6中使用脚本-Recaptcha

时间:2018-08-01 12:45:14

标签: javascript angular typescript recaptcha

我正在尝试在我的项目中实现recaptcha,但是我不确定如何使用它。

我以这种方式导入脚本:

public loadScript() {
let body = <HTMLDivElement>document.body;
let script = document.createElement('script');
script.innerHTML = '';
script.src = 'https://www.google.com/recaptcha/api.js';
script.async = true;
script.defer = true;
body.appendChild(script);
}

然后我在组件构造函数中调用此函数,并且可以正常工作-recaptcha可以正确渲染并可以正常工作,但是如何从后端获取响应?

我尝试了grecaptcha.getResponse(),但得到了ReferenceError: "grecaptcha is not defined"-有趣的是并不总是如此。那么如何使Typescript知道grecaptcha是什么呢?

1 个答案:

答案 0 :(得分:2)

  

要在Angular 4,5,6中使用Google reCAPTCHA v3,请按照简单的步骤

     

注册Google official Recaptcha website上的公钥

现在将以下脚本文件添加到角度项目 index.html

    <script src='https://www.google.com/recaptcha/api.js'></script>

然后在要使用验证码的组件文件中添加以下标记

<div class="form-group">
    <div id="captcha_element" class="g-recaptcha" 
     [attr.data-sitekey]="siteKeyCaptcha"></div>
</div>

现在使用以下代码更新您的 Typescript文件

declare var grecaptcha: any;

//declare Varible with public key given by Google
siteKeyCaptcha: string = "6LdF6xxxxxxxxxxxxxxxxxxxxxxxxxxxWVT";

//when we route back from the page we have to render captcha again
grecaptcha.render('capcha_element', {
  'sitekey': this.siteKeyCaptcha
});
  

要在点击添加回叫事件时从验证码获得响应,如下所示       在 HTML

**HTML**
<div class="form-group">
   <div id="capcha_element" class="g-recaptcha" 
   data-callback="getResponceCapcha" [attr.data-sitekey]="siteKeyCaptcha"></div>
</div>

**Typescript**
ngOnInit() {
  //....rest of code....
  window['getResponceCapcha'] = this.getResponceCapcha.bind(this);
}

getResponceCapcha(captchaResponse: string) {
   this.verifyCaptcha(captchaResponse);
}

verifyCaptcha(captchaResponse: string) {
  //you can do HTTP call from here
}
  

例如,单击here,然后单击here作为代码

相关问题