Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active September 26, 2019 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/11ac7e14f80c6f013c07f3e4a7a05b63 to your computer and use it in GitHub Desktop.
Save WebReflection/11ac7e14f80c6f013c07f3e4a7a05b63 to your computer and use it in GitHub Desktop.
// nullify the global reference while instrumenting the form
StaticEmail = (function (StaticEmail) {
// we don't know when window.recaptcha will be called,
// so we use a promise to simplify our workflow
var captcha = new Promise(function (resolve) {
window.recaptcha = function () {
// resolve passing the widget id along
resolve(
grecaptcha.render('recaptcha', {
// the SITE KEY reCAPTCHA provided
sitekey : 'yadaYadayAdayaDayadA'
})
);
};
});
contact.addEventListener('submit', function (event) {
event.preventDefault();
var from = contact.from.value.trim();
var md = contact.md.value.trim();
if (from && md) {
// asynchronous operations, better block the submit
contact.submit.disabled = true;
// whenever the external script lands ...
captcha.then(function (widget) {
// verify it's been clicked
var recaptcha = grecaptcha.getResponse(widget);
// if that's the case ...
if (recaptcha) {
// ensure it doesn't have a red outline anymore
document.querySelector('#recaptcha').className = '';
StaticEmail({
path: '/api/paperboy',
subject: 'Contact from ' + from,
from: from,
md: md,
// and pass the recaptcha token to StaticEmail
recaptcha: recaptcha
})
.then(
thanks,
function (error) {
// this check is to make code testable via http-server
if (
error.message === 'Method Not Allowed'
// handle 405 errors as either OK (75%) or errors
// if you don't want errors, comment the following line
&& Math.random() < .75
)
thanks();
else {
alert(error);
contact.submit.disabled = false;
}
}
);
}
// if reCAPTCHA was not clicked, outline it red
// to indicate it's mandatory (or use any other indication you like)
else {
document.querySelector('#recaptcha').className = 'invalid';
contact.submit.disabled = false;
}
});
}
});
function thanks() {
var div = document.createElement('div');
div.textContent = 'Thank You!';
contact.parentNode.replaceChild(div, contact);
}
}(StaticEmail));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment