3

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

但,

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

4

2 回答 2

1

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

declare const grecaptcha: any;

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

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

你也可以尝试安装typings @types/grecaptcha,得到一些类型提示,让你的生活更轻松一些。

于 2018-12-13T12:40:12.727 回答
0
  • 首先,确保您在index.html(不是 V2)中添加了 V3 reCaptcha 的正确脚本和 siteKey...正确的脚本和 siteKey 将帮助您加载外部 google 库并使其在window.grecaptcha. 我建议您另一种通过打字稿代码添加脚本的方法component.ts。只需在onInit()or中调用此函数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才能获取令牌。

于 2019-12-19T17:40:21.107 回答