Search code examples
angulartypescriptrecaptcha

How to execute recaptcha2 invisible? Angular 6


I've been working in adding an invisible captcha in my site, and searching the best way to do it, I follow the instructions provided here: https://github.com/Enngage/ngx-captcha

I notice the instructions in the section "reCaptcha v2" does not explain how to trigger the validation over the captcha, so I'm blocked because I find that the captcha works well, however, as the captcha is an additional component in my login page, it should trigger once the user clicks on 'submit' button.

The problem I have, is that it seems there is a missing variable that let me execute the callback function in the captcha as it explains here: https://developers.google.com/recaptcha/docs/invisible#programmatic_execute I see there is a variable (grecaptcha) with an 'execute()' function. So it takes into account the captcha validation.

At the moment, the code I have is following this structure: HTML: `

    <ngx-recaptcha2
    #captchaRef
    [siteKey]=captchaCode
    size="invisible"
    (resolved)="submitDataRC($event)"
    >
    </ngx-recaptcha2>

    <div>
         Form goes here...
         <button
         (click)="submitRecaptcha()"
         >Submit</button>
    </div>

`

TS `

@ViewChild('captchaRef') captchaRef: any;
captchaCode = 'abc'
        
      submitRecaptcha() {
        console.log('start submit method')   // I notice the execution prints this message
        console.log(this.captchaRef)
        this.navDisable = true;
        // this.captchaRef.execute() // This method is commented because it appears an error: execute is not a function of captchaRef
    }


        submitDataRC(captchaResponse: string) {  // I hope the captcha call this method with the token inside here
                code of the method here...
        }

`

I hope I explain my properly. Thanks in advance


Solution

  • If you are still looking for this, I found the execute() method in the grecaptcha property. It's a private property (so it's not really clean to use it) but I didn't find any other way to execute it programatically.

    So in your case it would be this.captchaRef.grecaptcha.execute().

    An other way would be to use ReCaptchaV3, which look easier to use in the typescript.

    Hope it helps.