Skip to content

Instantly share code, notes, and snippets.

@kkharji
Created March 5, 2024 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkharji/2a610f017937f5fc394325eed3830558 to your computer and use it in GitHub Desktop.
Save kkharji/2a610f017937f5fc394325eed3830558 to your computer and use it in GitHub Desktop.
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"
}));
});
}
});
}
// test.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);
};
onCleanup(() => {
// Remove badge
for (const badge of document.body.getElementsByClassName("grecaptcha-badge")) {
badge.remove();
}
// Remove injected script
for (const script of document.head.getElementsByTagName("script")) {
if (script.src.includes("recaptcha")) {
script.remove();
}
}
});
return (
<button onclick={onButtonClick}>
Click me
</button>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment