gpt4 book ai didi

angular - 在 angular 2/angular 4 中集成 recaptcha

转载 作者:搜寻专家 更新时间:2023-10-30 22:03:40 24 4
gpt4 key购买 nike

背景

我正在尝试将 re-captcha 集成到使用 angular 4 制作的单页应用程序中。我使用 grecaptcha.render(elt, {sitekey : 'XXX-my-public-key'}); 设置站点 key

问题

当我调用 grecaptcha.render() 时,我无法确定 recaptcha js 是否已加载。因此,有时,我会收到此错误:

LoginComponent_Host.html:1 ERROR ReferenceError: grecaptcha is not defined

问题

在调用 grecaptcha.render() 之前如何确定重新验证码已完全加载?

相关代码如下:

index.html

<html>
<head>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
</html>

login.component.html

<div #captchaDiv class="m-t"></div>

login.component.ts

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit, AfterViewInit {

@ViewChild('captchaDiv')
captchaDiv: ElementRef;

[...]

ngOnInit(): void {
grecaptcha.render(this.captchaDiv.nativeElement, {sitekey : 'XXX-my-public-key'});
}

最佳答案

聚会有点晚了,但我认为它对 future 的读者仍然有意义......

我认为您缺少的是脚本标记中的 asyncdefer 关键字,如以下指南中所示。

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

也就是说,下面是我的完整实现,以防标签需要动态添加和自定义为特定语言(这是我的需要)。我关注了 guide on google dev portal关于如何显式呈现 google recaptcha。

@Component({
template: `<div #recaptcha ></div>`
})
export class MyComponent implements AfterViewInit {
// Get a reference to the element which will hold the recaptcha widget
@ViewChild('recaptcha') recaptchaContainer:ElementRef;
// Retrieve this from your config
captchaKey:string = 'XXX-my-public-key';

constructor(private renderer:Renderer2) {}

ngAfterViewInit() {
this.initRecaptcha('en');
}

initRecaptcha(lang:string) {
// Check if recaptcha global variables are set, and if so, clear them.
// This is required in case you need to reload the recaptcha in a different language.
if (typeof grecaptcha !== 'undefined' && typeof recaptcha !== 'undefined' && typeof ___grecaptcha_cfg !== 'undefined') {
grecaptcha = recaptcha = ___grecaptcha_cfg = undefined;
}

// Clear the content of the element, and add div to be consumed by the script
this.recaptchaContainer.nativeElement.innerHTML = `<div class="g-recaptcha" data-sitekey="${this.captchaKey}"></div>`;

// Append the script to load
let script = this.renderer.createElement(this.recaptchaContainer.nativeElement, 'script');
this.renderer.setElementAttribute(script, 'innerHTML', '');
this.renderer.setElementAttribute(script, 'src', 'https://www.google.com/recaptcha/api.js?hl=' + lang);
this.renderer.setElementAttribute(script, 'async', 'true');
this.renderer.setElementAttribute(script, 'defer', 'true');
}
}

关于angular - 在 angular 2/angular 4 中集成 recaptcha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45658640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com