在角度6中使用脚本 - recaptcha

问题描述 投票:0回答:1

我正在尝试在我的项目中实现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" - 有趣的并不总是。那么如何让打字稿知道grecaptcha是什么?

javascript angular typescript recaptcha
1个回答
2
投票

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

注册Google official Recaptcha website上的公钥

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

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

然后在要使用Captcha的Component文件中添加以下标记

<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
});

要获取Captcha的响应,请在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代码

© www.soinside.com 2019 - 2024. All rights reserved.