首页 > 解决方案 > 如何在 Angular 4 项目中执行 reCAPTCHA

问题描述

想要使用 google reCaptcha 身份验证保护我的项目的 API 调用。但是从我的项目中调用 reCaptcha 方法时遇到问题。

这是谷歌文档中为 reCaptcha 提供的示例代码

 <script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
  <script>
  grecaptcha.ready(function() {//error on this line
      grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'}).then(function(token) {
         ...
      });
  });
  </script>

https://developers.google.com/recaptcha/docs/v3

为了实现这一点,我在我的 app.component.ts 中的 dom 中插入了源 url

const dynamicallyLoadScript = (url, options, callback) => {
    let script = document.createElement("script");
    script.type = "text/javascript";
    if (options.async) {
      script.async = true;
    }
    if (script.readyState) {
      //IE
      script.onreadystatechange = function() {
        if (script.readyState === "loaded" || script.readyState === "complete") {
          script.onreadystatechange = null;
          if (typeof callback === "function") {
            callback();
          }
        }
      };
    } else {
      //Others
      script.onload = function() {
        if (typeof callback === "function") {
          callback();
        }
      };
    }
    script.src = url;
    document.body.appendChild(script);
  };

在此之后,我调用了这个方法,如下所示: -

  window.loadingGrecaptcha = true;
  dynamicallyLoadScript("https://www.google.com/recaptcha/api.js?render=" + GetConfig.gToken, {}, () => {
    grecaptcha.ready(function() {
      window.loadingGrecaptcha = false;
    });
  });

我的 app.component

import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from './shared/services/authentication.service';

@Component({
  selector: 'admin-app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  isLoggedIn: boolean;
  grecaptcha: any;
  constructor(private authService: AuthenticationService) {
    authService.loggedIn$.subscribe(
      data => {
        this.ngOnInit();
      });
  }
  ngOnInit() {
    this.loadScript();
    this.isLoggedIn = this.authService.isAuthenticated();

    if (this.isLoggedIn) {
      this.authService.isLoggedIn();
    }
  }

  dynamicallyLoadScript = (url, options, callback) => {
    let script = document.createElement("script");
    script.type = "text/javascript";
    if (options.async) {
      script.async = true;
    }


    script.src = url;
    document.body.appendChild(script);
    callback();
  };

  loadScript() {
    this.dynamicallyLoadScript("https://www.google.com/recaptcha/api.js?render=" + this.authService.getGreToken(), {}, () => {
      this.grecaptcha.ready(function () {
        //window.loadingGrecaptcha = false;
      });
    });
  }
}

所以,从这里得到 grecaptcha 之后,我想从其他组件调用 grecaptcha.execute 。

在此处输入图像描述 但我正在准备不是 grecaptcha 中的功能。

提前致谢。

标签: javascriptangularrecaptcha

解决方案


推荐阅读