在 Aurelia 应用程序中使用 Google 的 reCAPTCHA

Use Google's reCAPTCHA in an Aurelia application

我一直在谷歌搜索,但似乎找不到在 Aurelia 应用程序中使用 reCAPTCHA 的方法。

如果可能,我想将其用作自定义元素。

import {inject, customElement} from 'aurelia-framework';

//maybe from url like https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit
import recaptcha from 'google-recaptcha';

@customElement('captcha')
@inject(recaptcha)
export class Captcha{

  constructor(recaptcha){
    this.recaptcha = recaptcha;
  }

  //add code to initialize captcha and handle callback
}

以下是创建显示 reCAPTCHA 的自定义元素的方法:

https://gist.run/?id=231c18eec8be2fa96169

recaptcha.js

import {inject, noView, bindable} from 'aurelia-framework';

const recaptchaCallbackName = 'setRecaptchaReady';
const ready = new Promise(resolve => window[recaptchaCallbackName] = resolve);

// https://developers.google.com/recaptcha/docs/display#explicit_render
let script = document.createElement('script');
script.src = `https://www.google.com/recaptcha/api.js?onload=${recaptchaCallbackName}&render=explicit`;
script.async = true;
script.defer = true;
document.head.appendChild(script);

const sitekey = '6LcddxgTAAAAAMmkEMa1Vrp6TNcZG8kMMkcn-VCK';

@noView()
@inject(Element)
export class Recaptcha {
  @bindable verified;
  @bindable theme = 'light';

  constructor(element) {
    this.element = element;
  }

  attached() {
    ready.then(() => grecaptcha.render(this.element, { 
      sitekey: sitekey, 
      theme: this.theme,
      callback: this.verified
    }));
  }
}

用法:

<template>
  <require from="./recaptcha"></require>

  <form action="?" method="POST">
    <!-- defaults -->
    <recaptcha></recaptcha>

    <!-- light theme, with callback -->
    <recaptcha theme="light" verified.call="onVerified()"></recaptcha>


    <!-- dark theme, with callback -->
    <recaptcha theme="dark" verified.call="onVerified()"></recaptcha>

    <br>
    <input type="submit" value="Submit">
  </form>
</template>