在React应用程序中定位Google Invisible Recaptcha

问题描述

因此,在我的React项目(一个很长的网站)中,我有一个提交表单位于页面的顶部。为了继续提交表单,必须经过Google Invisible Recaptcha验证。我为此使用了invisible-grecaptcha库。

const initCaptchaValidation = async (uuid) => {
    let token = await execute(key,{ locale: 'en' }); // Get Google recaptcha token

    /* Preparing to send POST request to verify recaptcha token */
    const f = new FormData();
    f.append('g-recaptcha-response',token);
    const response = await verifyCaptcha(f); // An axios call,to verify the token on the BE side

    destroy(); // Now destroy the captcha instance

    if (response.success){
      /* Proceed with form submission in here */
    }
    
  };

这里的问题是,验证码框打开的位置。由于我的网站很长,并且表单位于最顶部(这是设计使然,没有其他方法可以修改它。),因此,当验证码框呈现时,屏幕向下滚动到页面底部,并呈现验证码问题框。

我的想法是将验证码框(而不是徽章)呈现在表单所在的同一块中。而且由于该项目是使用React构建的,因此我无法获取验证码框的引用,从而无法操作该框。我唯一能做的就是使用MutationObserver,观察DOM中的变化并在渲染时捕获GIR框。

所以我创建了此实用程序以使用MutationObserver

export const ElementObserver = (target,cb) => {
  const config = { 
    childList: true,subtree: true,attributes: true,attributeOldValue: true 
  };
  const observer = new MutationObserver(cb);

  observer.observe(target,config);

  return () => observer.disconnect();
}

该返回值用于useEffect,用于清理目的

因此,在我要捕获框的页面中,在页面上渲染后,我会将窗口向上滚动到顶部,然后将验证码框重新定位到距顶部120px的位置。

useEffect(() => {
    const CaptchaHandler = () => {
      if (Boolean(document.querySelector('#invisible-captcha'))){
        console.log('Yes captcha is up!');

        let captchaElm = document.querySelector('#invisible-captcha'),nextElm = captchaElm.nextSibling;

          window.scrollTo(0,0);
          Boolean(nextElm.style) && nextElm.style.top = '120px';
      }
    }

    /* Utility to observe DOM changes */
    ElementObserver(document,CaptchaHandler);
  },[]);

但是这个问题是,有时页面会跳到最底部,然后突然上升。而且有时候验证码测试失败,然后再次打开,当我单击框中的答案时,框突然消失,然后再次出现。

我觉得上面的实现有问题。验证码很棒,但是在UX方面,它不能在很长的页面上使用。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)