Skip to content

Instantly share code, notes, and snippets.

@byrnedo
Last active November 30, 2020 16:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save byrnedo/a9d97c7094dbd929d8b5 to your computer and use it in GitHub Desktop.
Save byrnedo/a9d97c7094dbd929d8b5 to your computer and use it in GitHub Desktop.
/* global grecaptcha */
/* global $ */
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['g-recaptcha'],
attributeBindings: ['siteKey:data-sitekey', 'data-theme', 'data-size', 'data-callback', 'data-expired-callback', 'data-tabindex'],
siteKey: '',
lang: 'sv',
resetTrigger: false,
_isSetup: false,
_attempts: 0,
_maxAttempts: function(){
return 20;
}.property().readOnly(),
_interval: function() {
return 100; // Time between polls (in ms)
}.property().readOnly(),
verifyCallback: function(data){
Ember.$.ajaxPrefilter(function(options, oriOpt, jqXHR) {
jqXHR.setRequestHeader("X-Recaptcha-Token", data);
});
},
setupGrecaptcha: function(){
grecaptcha.render(this.$().prop('id'), {
'sitekey': this.get('siteKey'),
'callback' : this.verifyCallback,
});
this.set('_isSetup', true);
},
resetGrecaptcha: function(){
if(this.get('_isSetup') === true && this.get('resetTrigger') === true) {
grecaptcha.reset(this.$().prop('id'));
this.set('resetTrigger',false);
}
}.observes('resetTrigger'),
pollForObject: function(){
Ember.Logger.debug("Polling for grecaptcha");
if ( window.grecaptcha !== undefined ){
this.setupGrecaptcha();
} else if ( this.get('_attempts') < this.get('_maxAttempts') ) {
this.set('_attempts', this.get('_attempts') + 1);
Ember.run.later(this, function(){
this.pollForObject();
}, this.get('_interval'));
} else {
Ember.Logger.error("Failed to get grecapthca script");
}
},
init: function(){
this._super();
var self = this;
$.getScript("https://www.google.com/recaptcha/api.js?&render=explicit&hl=" + self.get('lang'), function( /*data, textStatus, jqxhr*/ ){
self.pollForObject();
});
}
});
@cravindra
Copy link

Hey!

Thanks for this. Very helpful.

However I did notice that when verifyCallbackwas called it appeared to have lost its component scope. Had to use the global window variable to keep reference of the component...

@byrnedo
Copy link
Author

byrnedo commented Jan 21, 2016

Hey @cravindra,

I'm so sorry, I never saw a notification about your comment!

About the verifyCallback issue, did you get it fixed? I see you've updated your fork. It's been a while since I worked with ember so I'm a little rusty with this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment