UNPKG

google-recaptcha-vue3

Version:

A lightweight Vue 3 component library supporting Google reCAPTCHA v2 and v3 integration.

61 lines (60 loc) 2.13 kB
import { onMounted as s, createElementBlock as u, openBlock as h, createElementVNode as w } from "vue"; const f = { __name: "Recaptcha", props: { siteKey: { type: String, required: !0 }, action: { type: String, default: "submit" }, // only for v3 hl: { type: String, default: "en" }, version: { type: String, default: "v3" }, // Added version prop autoLoad: { type: Boolean, default: !0 } // only for version: v2 }, emits: ["verify", "error", "expired"], setup(i, { expose: d, emit: p }) { const r = i, t = p; function n() { return new Promise((e, c) => { if (window.grecaptcha) return e(); const a = document.createElement("script"); a.src = r.version === "v2" ? `https://www.google.com/recaptcha/api.js?hl=${r.hl}` : `https://www.google.com/recaptcha/api.js?render=${r.siteKey}&hl=${r.hl}`, a.async = !0, a.defer = !0, a.onload = () => e(), a.onerror = () => c("Failed to load reCAPTCHA script."), document.head.appendChild(a); }); } function o() { if (!window.grecaptcha) { t("error", "reCAPTCHA library not loaded."); return; } try { window.grecaptcha.render("recaptcha-container", { sitekey: r.siteKey, callback: (e) => t("verify", e), "expired-callback": () => t("expired"), "error-callback": (e) => t("error", e || "Unknown reCAPTCHA v2 error") }); } catch (e) { t("error", `Error during reCAPTCHA v2 rendering: ${e.message}`); } } async function l() { try { await n(), r.version === "v2" ? o() : window.grecaptcha.ready(() => { window.grecaptcha.execute(r.siteKey, { action: r.action }).then((e) => t("verify", e)).catch((e) => t("error", e)); }); } catch (e) { t("error", e); } } return d({ execute: l }), s(async () => { r.version === "v2" && r.autoLoad && (await n(), o()); }), (e, c) => (h(), u("div", null, c[0] || (c[0] = [ w("div", { id: "recaptcha-container" }, null, -1) ]))); } }; export { f as default };