![](/img/trans.png)
[英]Angular recaptcha v3, code is showing error, not able to execute the function
[英]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);
}
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.