繁体   English   中英

reCAPTCHA v3 不工作 angular 6 - 执行错误

[英]reCAPTCHA v3 not working angular 6 - error executing

我正在使用 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);
});

但,

错误类型错误:无法读取未定义的属性“执行”

该对象应该可以从窗口获得,所以你需要的只是在你的 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 ,以获得一些类型提示,让您的生活更轻松

  • 首先,确保您在index.html (不是 V2)中添加了 V3 reCaptcha 的正确脚本和 siteKey...正确的脚本和 siteKey 将帮助您加载外部谷歌库并使其在window.grecaptcha可用。 我建议您通过在component.ts打字稿代码添加脚本的另一种方法。 只需在onInit()AfterViewInit()调用此函数onInit()
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);
 }
  • 其次,添加 script 和 sitekey 后,在你的component.ts ,只需要通过declare const window: any;来声明 window 对象declare const window: any;
  • 最后,当您的表单提交时:
window.grecaptcha.ready(function() {
        window.grecaptcha.execute(<sitekey>, {action: 'signup'}).then((token) => {
             //Do anything with captcha token
        });
    });

execute它以获取令牌之前, ready()函数确保从 google api 成功加载外部库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM