在shadow dom中渲染Google ReCaptcha

问题描述 投票:0回答:1

我们在渲染验证码时遇到一个错误: 未捕获的 DOMException:阻止了来源为“https://www.google.com”的框架访问跨源框架。

问题似乎是 ReCaptcha 不适用于 Shadow Dom。那么有没有什么解决方法呢。

在React中,我得到了一篇文章,说在shadow root外部渲染验证码并通过一些参考在shadow root内部使用它。 这是链接:https://medium.com/@tomas_26986/using-recaptcha-with-react-and-shadow-dom-abfd19fa03a

还有其他方法可以做到这一点吗?

javascript reactjs recaptcha shadow-dom
1个回答
0
投票

在使用

RecaptchaVerifier
时,我在使用 Firebase V9 SDK 中的
signInWithPhoneNumber
时遇到了类似的问题。我通过在我的 Web 组件中在
<DIV>
级别创建一个
Document
解决了这个问题,因为它确实看起来
ReCaptcha
在 Shadow DOM 中不起作用。

这段代码应该对您有帮助:

import { LitElement, html } from 'lit';
import { customElement } from 'lit/decorators.js';
import { RecaptchaVerifier, signInWithPhoneNumber } from 'firebase/auth';
import { auth } from '../libs/firebase-app.js';

@customElement('phone-auth-component')
export class PhoneAuthComponent extends LitElement {
  private recaptchaContainerId = 'recaptcha-container-global';

  firstUpdated() {
    // Ensure the div exists at the root level of the document
    this.ensureRecaptchaContainer();
    
    auth.languageCode = 'en';
    window.recaptchaVerifier = new RecaptchaVerifier(
      auth,
      this.recaptchaContainerId,
      {
        size: 'invisible',
        callback: (response) => {
          // reCAPTCHA solved, allow phoneNumber verification
          console.log('reCAPTCHA solved, allow phoneNumber verification');
        },
      }
    );
  }

  ensureRecaptchaContainer() {
    // Check if the container already exists
    let container = document.getElementById(this.recaptchaContainerId);
    if (!container) {
      // Create a new div and append it to the body
      container = document.createElement('div');
      container.id = this.recaptchaContainerId;
      document.body.appendChild(container);
    }
  }

  // Add the rest of your component logic here...
  
  render() {
    // Your render logic here...
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.