【问题标题】:reCAPTCHA v3 not working angular 6 - error executingreCAPTCHA v3 not working angular 6 - 执行错误
【发布时间】:2019-05-14 16:16:17
【问题描述】:

我正在使用 Angular 6 实施 Google reCAPTCHA v3。

<script src='https://www.google.com/recaptcha/api.js?render=KEY'></script>

index.html中添加了脚本

在我的 AppComponent 中,

constructor(
    @Inject(DOCUMENT) private document: any
) {
    this.grecaptcha = this.document.grecaptcha;
}

当我点击表单提交时,

this.grecaptcha.execute('KEY', { action: 'action_name' })
  .then(function (token) {
      // Verify the token on the server.
      console.log(token);
});

但是,

ERROR TypeError: Cannot read property 'execute' of undefined

【问题讨论】:

    标签: angular google-api recaptcha captcha recaptcha-v3


    【解决方案1】:
    • 首先,确保您在index.html(不是V2)中添加了V3 reCaptcha 的正确脚本和siteKey...正确的脚本和siteKey 将帮助您加载外部google 库并使其在@987654322 中可用@。 我建议您通过component.ts 中的打字稿代码添加脚本的另一种方法。只需在onInit()AfterViewInit() 中调用此函数即可。
    addScriptSrc() {
      let script: any = document.getElementById('script');
      if (!script) {
        script = document.createElement('script');
      }
      const body = document.body;
      script.innerHTML = '';
      script.src = 'https://www.google.com/recaptcha/api.js?render=<your_sitekey>';
      script.async = false;
      script.defer = true;
      body.appendChild(script);
     }
    
    • 其次,添加脚本和sitekey后,在你的component.ts中,只需要声明window对象 declare const window: any;
    • 最后,当您的表单提交时:
    window.grecaptcha.ready(function() {
            window.grecaptcha.execute(<sitekey>, {action: 'signup'}).then((token) => {
                 //Do anything with captcha token
            });
        });
    

    ready() 函数确保外部库已从 google api 成功加载,然后您 execute 获取令牌。

    【讨论】:

      【解决方案2】:

      该对象应该在窗口中可用,因此您只需在 ts 文件顶部声明它:

      declare const grecaptcha: any;
      

      然后你可以在你的课堂上使用它:

      grecaptcha.execute('KEY', { action: 'action_name' })
        .then(function (token) {
            // Verify the token on the server.
            console.log(token);
      })
      

      您也可以尝试安装打字@types/grecaptcha,以获得一些类型提示,让您的生活更轻松

      【讨论】:

      • Property 'grecaptcha' does not exist on type 'Window'
      • 仍然没有得到grecaptcha
      猜你喜欢
      • 1970-01-01
      • 2021-07-11
      • 2023-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 2021-05-01
      • 2015-09-29
      • 2020-10-02
      相关资源
      最近更新 更多