vue3-recaptcha-v2
Version:
reCAPTCHA for Vue3 : CompositionAPI, Types
104 lines (103 loc) • 3.27 kB
JavaScript
import { inject as g, defineComponent as b, ref as u, watch as m, onBeforeMount as R, onMounted as A, openBlock as _, createElementBlock as k } from "vue";
const E = "https://www.google.com/recaptcha/api.js", I = "https://recaptcha.net/recaptcha/api.js", C = "vue3-recaptcha-v2:options", p = "vue3-recaptcha-v2", s = typeof window > "u";
class a extends Error {
constructor(t) {
super(t), this.message = "[vue3-recaptcha-v2] " + t;
}
}
const x = () => {
const n = g(C);
return {
options: n,
handleGenerateScript: (o) => {
if (s)
throw new a("Cannot generate script on server side");
const e = document.getElementById(p);
e && e.remove();
const c = document.createElement("script"), i = n != null && n.cnDomains ? I : E, l = o ? `&hl=${o}` : "";
c.setAttribute("id", p), c.setAttribute("src", `${i}?render=explicit${l}`), c.setAttribute("async", ""), c.setAttribute("defer", ""), c.onerror = () => {
new a("Failed to load script");
}, document.head.appendChild(c);
}
};
}, y = () => ({
handleReset: (e) => {
if (s)
throw new a("reCaptcha is not available on server side");
if (!window.grecaptcha)
throw new a("reCaptcha is not available on window");
window.grecaptcha.reset(e);
},
handleGetResponse: (e) => {
if (s)
throw new a("reCaptcha is not available on server side");
if (!window.grecaptcha)
throw new a("reCaptcha is not available on window");
return window.grecaptcha.getResponse(e);
},
handleExecute: (e) => {
if (s)
throw new a("reCaptcha is not available on server side");
if (!window.grecaptcha)
throw new a("reCaptcha is not available on window");
window.grecaptcha.execute(e);
}
}), G = /* @__PURE__ */ b({
__name: "Recaptcha",
props: {
sitekey: {},
theme: {},
size: {},
tabindex: {},
language: {}
},
emits: ["widgetId", "loadCallback", "expiredCallback", "errorCallback"],
setup(n, { emit: t }) {
const o = n, e = u(null), c = u(null), { handleGenerateScript: i, options: l } = x(), h = (r) => {
if (!window.grecaptcha)
throw new a("reCAPTCHA is not loaded");
if (!c.value)
throw new a("element is not defined");
const { theme: w, size: f, tabindex: v } = o;
window.grecaptcha.ready(() => {
try {
e.value = window.grecaptcha.render(c.value, {
sitekey: r,
theme: w,
size: f,
tabindex: v,
callback: (d) => t("loadCallback", d),
"expired-callback": () => t("expiredCallback"),
"error-callback": () => t("errorCallback")
}), t("widgetId", e.value);
} catch (d) {
throw new a(d.message);
}
});
};
return m(
() => o.sitekey,
(r) => {
r && !e.value && h(r);
}
), R(() => {
i(o.language);
}), A(() => {
const { sitekey: r } = l;
document.getElementById(p).onload = () => {
r && h(r);
};
}), (r, w) => (_(), k("div", {
ref_key: "reCAPTCHARef",
ref: c
}, null, 512));
}
});
function O(n, t = {}) {
n.provide(C, t);
}
export {
G as RecaptchaV2,
O as install,
y as useRecaptcha
};