javascript - 如何在 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 。
提前致谢。
解决方案
推荐阅读
- c++ - 无法在 Visual Studio 代码(macOS 版本)中输入,高度赞赏解决方案
- javascript - offsetTop 返回 0
- sql - Full Outer Join 返回正确的结果,但 Order by 不完整
- c++ - 使用来自引用指针的信息来填充向量
- docker - 在 up -d docker 之后运行 shell 脚本
- javascript - 按钮提交表单的钩子调用无效
- c# - Unity 错误“不包含 'IsGameObjectInMainScenes' 的定义”
- node.js - 返回 POST 请求响应后运行方法
- r - 如何将 NA = 设置为两个不同的值?
- xml - IMPORTXML 将工具提示导入 Google 表格