[英]reCAPTCHA v3 not working angular 6 - error executing
I am implementing Google reCAPTCHA v3 with Angular 6.我正在使用 Angular 6 实现 Google reCAPTCHA v3。
<script src='https://www.google.com/recaptcha/api.js?render=KEY'></script>
Added script in index.html
在
index.html
添加脚本
In my AppComponent,在我的 AppComponent 中,
constructor(
@Inject(DOCUMENT) private document: any
) {
this.grecaptcha = this.document.grecaptcha;
}
and when i click form submit,当我点击表单提交时,
this.grecaptcha.execute('KEY', { action: 'action_name' })
.then(function (token) {
// Verify the token on the server.
console.log(token);
});
But,但,
ERROR TypeError: Cannot read property 'execute' of undefined
错误类型错误:无法读取未定义的属性“执行”
the object should be available from window, so all you need is to declare it on top of your ts file:该对象应该可以从窗口获得,所以你需要的只是在你的 ts 文件之上声明它:
declare const grecaptcha: any;
then you can use it in your class like:然后你可以在你的课堂上使用它,比如:
grecaptcha.execute('KEY', { action: 'action_name' })
.then(function (token) {
// Verify the token on the server.
console.log(token);
})
You can also try to install the typings @types/grecaptcha
, to get some type hinting to make your life a bit easier您也可以尝试安装
@types/grecaptcha
,以获得一些类型提示,让您的生活更轻松
index.html
(not V2)... The right script and siteKey will help you to load external google library and make it available in window.grecaptcha
.index.html
(不是 V2)中添加了 V3 reCaptcha 的正确脚本和 siteKey...正确的脚本和 siteKey 将帮助您加载外部谷歌库并使其在window.grecaptcha
可用。 I suggest you another way to add script by typescript code in your component.ts
.component.ts
打字稿代码添加脚本的另一种方法。 Just call this function in onInit()
or AfterViewInit()
.onInit()
或AfterViewInit()
调用此函数onInit()
。addScriptSrc() {
let script: any = document.getElementById('script');
if (!script) {
script = document.createElement('script');
}
const body = document.body;
script.innerHTML = '';
script.src = 'https://www.google.com/recaptcha/api.js?render=<your_sitekey>';
script.async = false;
script.defer = true;
body.appendChild(script);
}
component.ts
, just need to declare the window object by declare const window: any;
component.ts
,只需要通过declare const window: any;
来声明 window 对象declare const window: any;
window.grecaptcha.ready(function() {
window.grecaptcha.execute(<sitekey>, {action: 'signup'}).then((token) => {
//Do anything with captcha token
});
});
ready()
function make sure that the external library is successfully loaded from google api, before you execute
it to get token.在
execute
它以获取令牌之前, ready()
函数确保从 google api 成功加载外部库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.