Reputation: 2166
I am implementing Google reCAPTCHA v3 with Angular 6.
<script src='https://www.google.com/recaptcha/api.js?render=KEY'></script>
Added script in index.html
In my 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
Upvotes: 3
Views: 4996
Reputation: 111
index.html
(not V2)... The right script and siteKey will help you to load external google library and make it available in window.grecaptcha
.
I suggest you another way to add script by typescript code in your component.ts
. Just call this function in onInit()
or AfterViewInit()
.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;
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.
Upvotes: 1
Reputation: 71911
the object should be available from window, so all you need is to declare it on top of your ts file:
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
Upvotes: 1