import { Inject , Injectable } from "@angular/core" ; import { Observable , Subscriber } from "rxjs" ; import { loadHCaptcha } from "./hcaptcha-utils" ; import { CaptchaConfig , CAPTCHA_CONFIG } from "./ng-hcaptcha-config" ; declare const window ; @ Injectable ( ) export class NgHcaptchaService { private hCaptchaElement : HTMLElement ; private hCaptchaWidgetId : string ; constructor ( @ Inject ( CAPTCHA_CONFIG ) private captchaConfig ) { } verify ( ) { return new Observable ( ( subscriber ) => { loadHCaptcha ( this . captchaConfig . languageCode ) . subscribe ( ( ) => { setTimeout ( ( context ) => { if ( ! this . hCaptchaElement ) { this . hCaptchaElement = document . createElement ( 'div' ) ; document . body . appendChild ( this . hCaptchaElement ) ; } if ( ! this . hCaptchaWidgetId ) { const options = { sitekey : this . captchaConfig . siteKey , size : 'invisible' , callback : ( res ) => { subscriber . next ( res ) ; subscriber . complete ( ) ; this . resetHcaptcha ( ) ; } , 'expired-callback' : ( res ) => { subscriber . error ( res ) ; this . resetHcaptcha ( ) ; } , 'error-callback' : ( err ) => { subscriber . error ( err ) ; this . resetHcaptcha ( ) ; } , } ; this . hCaptchaWidgetId = window . hcaptcha . render ( this . hCaptchaElement , options ) ; } window . hcaptcha . execute ( this . hCaptchaWidgetId ) ; } , 50 , this ) ; } ) ; } ) ; } private resetHcaptcha ( ) { window . hcaptcha . remove ( this . hCaptchaWidgetId ) ; this . hCaptchaElement = null ; this . hCaptchaWidgetId = null ; } }