asubanovsky asubanovsky - 1 month ago 36
TypeScript Question

Angular 2 Recaptcha 2 Callback

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?

Answer

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);
  }
}
Comments