musescore-downloader/src/recaptcha.ts
2020-03-08 17:36:37 -04:00

48 lines
1.2 KiB
TypeScript

/**
* the site key for Google reCAPTCHA v3
*/
const SITE_KEY = "6Ldxtt8UAAAAALvcRqWTlVOVIB7MmEWwN-zw_9fM"
type token = string;
interface GRecaptcha {
ready(cb: Function): void;
execute(siteKey: string, opts: { action: string }): Promise<token>;
}
let gr: GRecaptcha | Promise<GRecaptcha>
/**
* load reCAPTCHA
*/
const load = (): Promise<GRecaptcha> => {
// load script
const script = document.createElement("script")
script.src = `https://www.google.com/recaptcha/api.js?render=${SITE_KEY}`
script.async = true
document.body.appendChild(script)
// add css
const style = document.createElement("style")
style.innerHTML = ".grecaptcha-badge { display: none !important; }"
document.head.appendChild(style)
return new Promise((resolve) => {
script.onload = () => {
const grecaptcha: GRecaptcha = window["grecaptcha"]
grecaptcha.ready(() => resolve(grecaptcha))
}
})
}
export const init = () => {
if (!gr) {
gr = load()
}
return gr
}
export const execute = async (): Promise<token> => {
const captcha = await init()
return captcha.execute(SITE_KEY, { action: "downloadmscz" })
}