【问题标题】:Using scripts in angular 6 - recaptcha在 Angular 6 中使用脚本-recaptcha
【发布时间】:2019-01-09 01:06:32
【问题描述】:

我正在尝试在我的项目中实现 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 是什么?

【问题讨论】:

标签: javascript angular typescript recaptcha


【解决方案1】:

要在 Angular 4、5、6 中使用 Google reCAPTCHA v3,请按照以下简单步骤操作

Google official Recaptcha website注册公钥

现在在您的 Angular 项目中添加以下脚本文件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获取代码

【讨论】:

    猜你喜欢
    • 2019-03-16
    • 2019-08-03
    • 1970-01-01
    • 2018-10-31
    • 2019-01-17
    • 1970-01-01
    • 2019-05-14
    • 2021-04-25
    • 2019-03-20
    相关资源
    最近更新 更多