问题
How to Integrate reCAPTCHA in your Angular 2 Application?
回答1:
Assuming that you have Site Key and Client Secret given by reCAPTCHA. Put below code in component.
@ViewChild('captchaRef2') captchaRef2: ElementRef;
private _reCaptchaId: number;
private SITE_ID = [YourSiteKey];
ngAfterViewInit() {
const grecaptcha = (window as any).grecaptcha;
if (grecaptcha) {
this._reCaptchaId = grecaptcha.render(this.captchaRef2.nativeElement, {
'sitekey': this.SITE_ID,
'callback': (resonse) => this.reCapchaSuccess(resonse),
'expired-callback': () => this.reCapchaExpired()
});
}
}
Below is the Success callback function. If the response data has value then reCAPTCHA verified successfully.
reCapchaSuccess(data:any){
if(data){
alert("Congratulation! reCAPTCHA verified.")
// Some logic goes here
}
}
Below function will be called when reCAPTCHA expired.
reCapchaExpired(){
alert("Oops! reCAPTCHA expired.")
// Some logic goes here
}
Put below div in the HTML file.
<div #captchaRef2></div>
Put below JS script in index.html file.
<script src='https://www.google.com/recaptcha/api.js?render=explicit" async defer'></script>
回答2:
By putting above js script, sometimes I face below error: "grecaptcha.render is not a function" so, in case you face this error just use following js script instead of above
<script src="https://www.google.com/recaptcha/api.js?render=explicit" async defer></script>
cheers!
回答3:
Why overcomplicating that much if ng-recaptcha exists?
yarn add ng-recaptcha
ornpm i ng-recaptcha --save
In one of your modules (such as
app.module.ts
,shared.module.ts
, etc.)
(like explained here)
import { RecaptchaModule, RECAPTCHA_SETTINGS, RecaptchaSettings } from 'ng-recaptcha';
@NgModule({
imports: [RecaptchaModule],
providers: [
{
provide: RECAPTCHA_SETTINGS,
useValue: { siteKey: '<YOUR_KEY>' } as RecaptchaSettings,
},
],
}) export class MyModule { }
- Use it in your
html
as<re-captcha>
来源:https://stackoverflow.com/questions/48902711/how-to-add-recaptcha-in-angular-2-application