Installer avec Angular
Un composant Angular autonome qui affiche le widget.
Sur cette page
Le chargeur
// scaptcha.ts
export interface ScaptchaApi {
render(el: HTMLElement, options: Record<string, unknown>): string;
reset(id?: string): void;
remove(id?: string): void;
getResponse(id?: string): string;
execute(id?: string): Promise<string>;
}
let loading: Promise<ScaptchaApi> | null = null;
export function loadScaptcha(): Promise<ScaptchaApi> {
const w = window as unknown as { scaptcha?: ScaptchaApi };
if (w.scaptcha) return Promise.resolve(w.scaptcha);
loading ??= new Promise<ScaptchaApi>((resolve, reject) => {
const s = document.createElement("script");
s.src = "https://api.scaptcha.xyz/api.js?render=explicit";
s.async = true;
s.onload = () => (w.scaptcha ? resolve(w.scaptcha) : reject(new Error("scaptcha")));
s.onerror = () => {
loading = null;
s.remove();
reject(new Error("network"));
};
document.head.append(s);
});
return loading;
}Le composant
import { AfterViewInit, Component, ElementRef, EventEmitter, Input, OnDestroy, Output, ViewChild } from "@angular/core";
import { loadScaptcha, type ScaptchaApi } from "./scaptcha";
@Component({ selector: "app-scaptcha", standalone: true, template: "<div #box></div>" })
export class ScaptchaComponent implements AfterViewInit, OnDestroy {
@Input({ required: true }) sitekey!: string;
@Input() action = "";
@Output() token = new EventEmitter<string>();
@ViewChild("box") box!: ElementRef<HTMLDivElement>;
private api?: ScaptchaApi;
private id = "";
private gone = false;
async ngAfterViewInit() {
this.api = await loadScaptcha();
if (this.gone) return;
this.id = this.api.render(this.box.nativeElement, {
sitekey: this.sitekey,
action: this.action,
callback: (t: string) => this.token.emit(t),
"expired-callback": () => this.token.emit(""),
});
}
ngOnDestroy() {
this.gone = true;
if (this.id) this.api?.remove(this.id);
}
}Envoyer le jeton
Joignez la valeur émise par (token) à votre requête, vérifiez-la dans votre API, puis détruisez ou réinitialisez le widget avant un nouvel envoi.
Le jeton reçu dans le navigateur ne prouve rien à lui seul : vérifiez-le sur votre serveur.
Dernière mise à jour :