Created
March 5, 2024 09:57
-
-
Save kkharji/2a610f017937f5fc394325eed3830558 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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