是否有任何reCAPTCHA v2关闭事件?
我正在使用如下代码呈现grecaptcha
let callback;
const p = new Promise((resolve) => callback = (result) => resolve(result));
grecaptcha.render(el, {
sitekey: window.settings.recaptchaKey,
size: "invisible",
type: "image",
callback: result => callback(result),
badge: "inline"
});
const key = await p;
一切正常,但如果用户点击reCAPTCHA模式的背景,reCAPTCHA关闭,我检测不到它,所以我无限地等待响应
我需要某种事件或回调来检测它何时关闭
解决方案
作为一种肮脏的解决办法,我们可以设置超时并等待reCAPTCHA IFRAME显示,然后等待它隐藏
我制作了进行所有操作的模块
它依赖于jQuery和全局reCAPTCHA
我是这样使用它的
try {
key = await captcha(elementToBind, 'yoursitekey');
}
catch (error) {
console.log(error); // when recaptcha canceled it will print captcha canceled
}
糟糕的是,当Google更改html结构中的某些内容时,它可能会崩溃
模块代码
/* global grecaptcha */
import $ from "jquery";
let callback = () => {};
let hideCallback = () => {};
export default function captcha (el, sitekey) {
const $el = $(el);
el = $el[0];
let captchaId = $el.attr("captcha-id");
let wrapper;
if (captchaId == null) {
captchaId = grecaptcha.render(el, {
sitekey,
size: "invisible",
type: "image",
callback: result => callback(result),
badge: "inline",
});
$(el).attr("captcha-id", captchaId);
}
else {
grecaptcha.reset(captchaId);
}
const waitForWrapper = setInterval(() => {
// first we search for recaptcha iframe
const iframe = $("iframe").filter((idx, iframe) => iframe.src.includes("recaptcha/api2/bframe"));
iframe.toArray().some(iframe => {
const w = $(iframe).closest("body > *");
// find the corresponding iframe for current captcha
if (w[0] && !w[0].hasAttribute("captcha-id") || w.attr("captcha-id") == captchaId) {
w.attr("captcha-id", captchaId);
wrapper = w; // save iframe wrapper element
clearInterval(waitForWrapper);
return true;
}
});
}, 100);
const result = new Promise((resolve, reject) => {
callback = (result) => {
clearInterval(waitForHide);
resolve(result);
};
hideCallback = (result) => {
clearInterval(waitForHide);
reject(result);
};
});
grecaptcha.execute(captchaId);
let shown = false;
const waitForHide = setInterval(() => {
if (wrapper) { // if we find iframe wrapper
if (!shown) {
// waiting for captcha to show
if (wrapper.css("visibility") !== "hidden") {
shown = true;
console.log("shown");
}
}
else {
// now waiting for it to hide
if (wrapper.css("visibility") === "hidden") {
console.log("hidden");
hideCallback(new Error("captcha canceled"));
}
}
}
}, 100);
return result;
}
相关文章