react-google-recaptcha-hook
Version:
React Hook for Google reCAPTCHA v3
51 lines (50 loc) • 1.96 kB
JavaScript
import { useCallback as h, useRef as l, useEffect as n } from "react";
const g = (c) => new Promise((e) => {
var a;
window.___grecaptcha_cfg ?? (window.___grecaptcha_cfg = {
fns: []
}), c ? (a = window.grecaptcha) != null && a.enterprise ? e(window.grecaptcha.enterprise) : window.___grecaptcha_cfg.fns.push(() => {
e(window.grecaptcha.enterprise);
}) : window.grecaptcha ? e(window.grecaptcha) : window.___grecaptcha_cfg.fns.push(() => {
e(window.grecaptcha);
});
}), f = async (c, e, a) => (await g(c)).execute(e, { action: a }), m = async (c) => {
(await g(c)).ready(() => {
const a = document.querySelector(".grecaptcha-badge");
a && (a.style.visibility = "hidden");
});
}, _ = async (c) => {
(await g(c)).ready(() => {
const a = document.querySelector(".grecaptcha-badge");
a && (a.style.visibility = "visible");
});
}, y = (c, e) => {
const a = e != null && e.language ? `&hl=${e.language}` : "", t = e != null && e.enterprise ? "enterprise.js" : "api.js";
return `https://www.${e != null && e.recaptchaNet ? "recaptcha.net" : "google.com"}/recaptcha/${t}?render=${c}${a}`;
}, b = (c, e) => {
const a = h(() => {
if (document.getElementById(c))
return;
const r = document.createElement("script");
r.async = !0, r.type = "text/javascript", r.src = y(c, e), r.id = c, document.getElementsByTagName("head")[0].appendChild(r);
}, [e, c]), t = h(
() => m(!!(e != null && e.enterprise)),
[e == null ? void 0 : e.enterprise]
), d = h(
() => _(!!(e != null && e.enterprise)),
[e == null ? void 0 : e.enterprise]
), w = h(
(r) => f(!!(e != null && e.enterprise), c, r),
[e == null ? void 0 : e.enterprise, c]
), u = l(!1);
return n(() => {
u.current || (u.current = !0, e != null && e.hide && t(), a());
}, [a, t, e]), {
executeGoogleReCaptcha: w,
hideGoogleReCaptcha: t,
showGoogleReCaptcha: d
};
};
export {
b as useGoogleReCaptcha
};