Skip to content

Instantly share code, notes, and snippets.

@bh3605
Created September 28, 2017 18:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bh3605/98d495bc05ee5428ed62893c0810449a to your computer and use it in GitHub Desktop.
Save bh3605/98d495bc05ee5428ed62893c0810449a to your computer and use it in GitHub Desktop.
knockout way of building a recaptcha
/**
* Make sure your page is using <script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
* or if you're using <script src="https://www.google.com/recaptcha/api.js" async defer></script> then comment out
* Recaptcha.create and uncomment the grecaptcha.render.
* based on http://jsfiddle.net/jaGWY/
* docs: https://developers.google.com/recaptcha/intro & http://recaptchamvc.apphb.com/Home/Document
*/
var app = app || {};
app.knockout = app.knockout || {};
app.knockout.recaptcha = (function ($) {
var key = app.recaptchaPublicKey;
var widgetId = null;
ko.bindingHandlers['recaptcha'] = {
'init': function (element, valueAccessor, allBindingsAccessor, viewModel) {
var val = ko.utils.unwrapObservable(valueAccessor()),
response = val.response;
$(function () {
$(app).on("createCaptcha", function (event, theme) {
widgetId = grecaptcha.render("recaptcha",
{
'sitekey': key,
'theme': theme,
'callback': function () {
var responseId = "g-recaptcha-response";
responseElement = document.getElementById(responseId);
if (ko.isObservable(response))
response(responseElement.value);
else
response = responseElement.value;
},
'expired-callback': function () {
grecaptcha.reset(widgetId);
}
});
//Recaptcha.create(key,
// element.id,
// {
// theme: "clean",
// callback: function (/*none supplied by google, thanks*/) {
// var responseId = 'recaptcha_response_field', challengeId = 'recaptcha_challenge_field',
// challengeElement = document.getElementById(challengeId),
// responseElement = document.getElementById(responseId);
// if (ko.isObservable(challenge))
// challenge(challengeElement.value);
// else
// challenge = challengeElement.value;
// $(responseElement).on("change", function () {
// if (ko.isObservable(response))
// response(this.value);
// else
// response = this.value;
// });
// }
// }
// );
});
});
}
};
var model = {};
model.reset = function () {
grecaptcha.reset(widgetId);
};
return model;
})(jQuery);
var onloadCallback = function () {
jQuery(app).trigger("createCaptcha"); // pass 2nd arg as ["dark"] to make captcha black
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment