basaran / svelte-recaptcha-v2

Google reCAPTCHA v2 implementation for Svelte SPA, SSR and sveltekit static sites.
https://basaran.github.io/svelte-recaptcha-v2/demo
MIT License
42 stars 14 forks source link

Invisible captcha giving timeout on Promise.resolve(observer) #21

Open gregg-cbs opened 3 months ago

gregg-cbs commented 3 months ago

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.

kyrregjerstad commented 3 months ago

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

gregg-cbs commented 3 months ago

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>