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

时间:2016-02-16 19:50:20

标签: javascript recaptcha aurelia

我一直在谷歌搜索,但我似乎无法在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
}

1 个答案:

答案 0 :(得分:4)

以下是如何创建显示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>