svelte-recaptcha-v2 icon indicating copy to clipboard operation
svelte-recaptcha-v2 copied to clipboard

Invisible captcha giving timeout on Promise.resolve(observer)

Open gregg-cbs opened this issue 1 year ago • 2 comments

As per your instructions we are doing:

recaptcha.execute()
Promise.resolve(observer)

But observer seems to hang when trying to resolve its promise. We cant seem to get past this.

gregg-cbs avatar May 22 '24 14:05 gregg-cbs

@gregg-cbs I'm facing the same issue, did you find a solution?

kyrregjerstad avatar May 29 '24 11:05 kyrregjerstad

Yes I did, the docs are very wrong. This should help you @kyrregjerstad, not perfect but it works and you can do what you need with it.

<script lang="ts">
  import { Recaptcha, recaptcha } from 'svelte-recaptcha-v2';

  let loading = false;
  let init_recaptcha = false;

  // Put this inside an env file.
  const RECAPTCHA_SITE_KEY = 'your recapthca key';

  // to know if captcha is successfully initiated
  const onCaptchaReady = (event: any) => {
    init_recaptcha = true;
  };

  // this happens automatically after form submit
  const onCaptchaSuccess = async (event: any) => {
    loading = true;
    
    if (event.detail.token) {
      await onSubmit();
    }
    
    loading = false;
  };

  // if captcha fails to init
  const onCaptchaError = (event: any) => {
    init_recaptcha = false;
    // log a message to yourself to know
  };

  function onCaptchaSubmit() {
    loading = true;
    // over here we are bypassing captcha if it failed to init
    // so at least users can still submit the form
    if (init_recaptcha) {
      recaptcha.execute(); // this will fire onCaptchaSuccess
    } else {
      // log to yourself to let you know captcha is failing to initialise
      
      // but submit the form in any case to not block users
      onSubmit();
    }
    
    loading = false;
  }

  async function onSubmit() {
    // do whatever you want with your formdata and send it somewhere
  }
</script>
</script>

<form
  on:submit|preventDefault={onCaptchaSubmit}
>
  <Recaptcha
    class="self-center"
    sitekey={RECAPTCHA_SITE_KEY}
    badge={'top'}
    size="invisible"
    on:success={onCaptchaSuccess}
    on:error={onCaptchaError}
    on:ready={onCaptchaReady}
  />
</form>

gregg-cbs avatar May 30 '24 09:05 gregg-cbs