我已将 google recapcha 集成到 vite-react-ts 应用程序中并创建了它的构建。
const script = document.createElement('script');
script.src = url;
script.async = true;
script.defer = true;
script.onload = renderCaptcha;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
const renderCaptcha = () => {
if (window?.grecaptcha) {
try {
if (captchaRef.current.captcha) {
captchaRef.current = { ...captchaRef.current, pendingCaptcha: true };
window?.grecaptcha.reset(captchaRef.current.captcha);
} else {
const captcha = window?.grecaptcha.render(captchaContainerRef.current, {
sitekey: CAPTCHA_V2_KEY,
callback: () => {
captchaRef.current = { ...captchaRef.current, pendingCaptcha: false };
},
'expired-callback': (data: any) => {
console.log("expired")
console.log(data)
},
'error-callback': (error: any) => {
console.log("error")
console.log(error)
}
});
captchaRef.current = { ...captchaRef.current, captcha, pendingCaptcha: true };
}
} catch (e) {
console.error('captcha generation error', e);
}
}
};
JSX
<div ref={captchaContainerRef} id="signin_captcha" />
现在我正在尝试使用其他应用程序中的脚本标签加载此版本。
我收到错误
Uncaught DOMException: Blocked a frame with origin "https://www.google.com" from accessing a cross-origin frame.
做了一些研究来找到一种方法,看起来不可能,因为它是浏览器本身的拦截器。
我现在唯一能做的解决方案是将 recaptcha 与文档正文而不是我的应用程序一起附加,这将允许访问 recaptcha 的 DOM 并且它将起作用。