class SimpleCaptcha extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
}
connectedCallback() {
this.render();
}
render() {
this.shadowRoot.innerHTML = `
`;
const img = this.shadowRoot.getElementById("img");
img.addEventListener("click", () => this.refresh());
this.shadowRoot.getElementById("refresh")
.addEventListener("click", () => this.refresh());
this.shadowRoot.getElementById("submit")
.addEventListener("click", () => this.handleSubmit());
}
refresh() {
const img = this.shadowRoot.getElementById("img");
img.src = "captcha.php?" + Date.now();
this.shadowRoot.getElementById("input").value = "";
}
async validate() {
const input = this.shadowRoot.getElementById("input").value.trim();
if (!input) return false;
const formData = new FormData();
formData.append("captcha", input);
try {
const res = await fetch("validate.php", { method: "POST", body: formData });
const data = await res.json();
return data.status === "valid";
} catch (err) {
console.error("Captcha validation failed:", err);
return false;
}
}
async handleSubmit() {
const isValid = await this.validate();
if (isValid) {
this.dispatchEvent(new CustomEvent("valid"));
this.refresh();
} else {
this.dispatchEvent(new CustomEvent("invalid"));
this.refresh();
}
}
}
customElements.define("simple-captcha", SimpleCaptcha);