javascript - 在 Angular 6 中使用脚本 - recaptcha

标签 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 Define" - 有趣的并不总是如此。那么如何让 Typescript 知道 grecaptcha 是什么?

最佳答案

To Use Google reCAPTCHA v3 in Angular 4,5,6 follow the simple steps

Register For the public key on 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
});

To get a Response from Captcha on click add call back event as follows in 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
}

Click here for example and here for code

关于javascript - 在 Angular 6 中使用脚本 - recaptcha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51633644/

相关文章:

javascript - 如何在 Firestore 数据库中检索 document.id?

javascript - 如何让 Angular 在 ajax get 之后更新集合

javascript - jQuery 在鼠标悬停时淡入

javascript - 如何从 Chrome 扩展程序中检查 HTML 元素是否可内容

angular - ngx-translate 与 ts 文件上的动态文本

angular - 如何使用 HttpClient 请求 Angular 6 中的非 json 八位字节流?

javascript - 为什么 ngOnChange 没有检测到 @Input 元素更改而 ngOnDetect 能够这样做

node.js - 在类中排序 RESTful API 方法的最佳实践

javascript - writeFile 从数组到新行将不起作用

javascript - 我是否需要学习 CSS3 和 HTML 基础知识才能制作 HTML5 游戏和动态 Web 应用程序?