簡體   English   中英

reCAPTCHA v3 不工作 angular 6 - 執行錯誤

[英]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);
 }
  • 其次,添加 script 和 sitekey 后,在你的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM