Currently I'm trying to use Google Recaptcha v2 in Angular 2 Typescript. I use it in Sign Up form. Suppose I have a form containing:
<form id="signup-form">
<div class="g-recaptcha" data-callback="verifyCallback" data-sitekey="6LetChQTAAAAACq4lmSL0L1-4rv47ZPrFKrkWOLf"></div>
</div>
And in my Signup class, I use the following code to display the widget in the method named displayRecaptcha():
displayRecaptcha(){
var doc = <HTMLDivElement>document.getElementById('signup-form');
var script = document.createElement('script');
script.innerHTML = '';
script.src = 'https://www.google.com/recaptcha/api.js';
script.async = true;
script.defer = true;
doc.appendChild(script);
var d = document.createElement('script');
d.innerHTML = `
var verifyCallback() = function(response) {
alert(response);
};`
document.querySelector('head').appendChild(d);
}
With above codes, I'm able to display the recaptcha, but I only able to run the callback using verifyCallback() which is defined in the Javascript. As I'm using the Typescript, is there anyway to make the callback runs using the method defined inside the Signup class instead of Javascript?
Just in case anybody finds it useful, I had also come up with a solution for integrating Google reCAPTCHA into my Angular forms and I released it as a library here:
https://github.com/JamesHenry/angular-google-recaptcha
It gives you a dead simple Component which can be used with either template driven or reactive forms:
<recapthca [(ngModel)]="" (scriptLoad)="" (scriptError)="">
<recapthca [formControl]="" (scriptLoad)="" (scriptError)="">
It means you don't need to worry about registering global callbacks, or handling script loading at all! 🚀
I don't think that you will be able to pass a callback reference to the script, however you could patch it through by using a global variable that the typescript will then have access to.
@Component({...})
export class MyComponent{
constructor(){
window['verifyCallback'] = this.verifyCallback.bind(this);
}
displayRecaptcha(){
var doc = <HTMLDivElement>document.getElementById('signup-form');
var script = document.createElement('script');
script.innerHTML = '';
script.src = 'https://www.google.com/recaptcha/api.js';
script.async = true;
script.defer = true;
doc.appendChild(script);
}
verifyCallback(response){
alert(response);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With