Mel*_*or_ 1 javascript recaptcha typescript angular
我正在尝试在我的项目中实现 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);
}
Run Code Online (Sandbox Code Playgroud)
然后我在组件构造函数中调用这个函数,它可以工作 - recaptcha 被正确呈现并且可以工作,但是如何从中获得对我的后端的响应?
我试过了,grecaptcha.getResponse()但我明白了ReferenceError: "grecaptcha is not defined"- 有趣的事情并不总是如此。那么如何让 Typescript 知道 grecaptcha 是什么?
要在 Angular 4、5、6 中使用 Google reCAPTCHA v3,请按照简单的步骤操作
在谷歌官方 Recaptcha 网站上注册获取公钥
现在在您的角度项目index.html 中添加以下脚本文件
<script src='https://www.google.com/recaptcha/api.js'></script>
Run Code Online (Sandbox Code Playgroud)
然后在您要使用 Captcha 的组件文件中添加以下标签
<div class="form-group">
<div id="captcha_element" class="g-recaptcha"
[attr.data-sitekey]="siteKeyCaptcha"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
现在使用以下代码更新您的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
});
Run Code Online (Sandbox Code Playgroud)
要在单击时从 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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3332 次 |
| 最近记录: |