#Using Recaptcha

2 messages · Page 1 of 1 (latest)

narrow pecan
#

So I'm trying to use Recaptcha on my site, I found another person in this discord talking about it who gave some code they used to get it working, which I based mine of.

This is my code for a Recaptcha loader:

recaptcha.ts

declare var grecaptcha: {
    ready: (callback: () => void) => void;
    execute: (siteKey: string, opts: { action: "submit" }) => Promise<string>;
};

export type CodeFunction = () => Promise<string>;

export default function(setter: (fn: CodeFunction) => void) {
    const siteKey = import.meta.env.VITE_CAPTCHA_SITE_KEY;
    createScriptLoader({
        src: `https://www.google.com/recaptcha/api.js?render=${siteKey}`,
        onload: async () => {
            grecaptcha.ready(() => {
                setter(() => grecaptcha.execute(siteKey, {
                    action: "submit"
                }));
            });
        }
    });
}```

And I'm using it like this:

`test.tsx`
```ts
import {onMount} from "solid-js";
import addCaptcha, {CodeFunction} from "~/lib/recaptcha";

export default function() {
    let codeFn: CodeFunction;
    onMount(() => {
        addCaptcha(fn => {
            codeFn = fn;
            console.log("Loaded captcha");
        });
    });
    const onButtonClick = async () => {
        if (!codeFn) {
            return console.error("Captcha not ready");
        }
        const token = await codeFn();
        console.log(token);
    };
    return (
        <button onclick={onButtonClick}>
            Click me
        </button>
    );
}

It seems to work, but I'm not sure if this is the best implementation and would like some feedback. There is also the issue that the captcha widget persists on the page when I navigate to another page on my website, how can I prevent this?

narrow pecan
#

If i switch between different pages it also keeps adding new captchas every time i go back to the test page