Skip to content

Instantly share code, notes, and snippets.

@benaubin
Last active May 3, 2020 22:26
Show Gist options
  • Save benaubin/aea4ed964f30399b23e7b347fcfe9d8d to your computer and use it in GitHub Desktop.
Save benaubin/aea4ed964f30399b23e7b347fcfe9d8d to your computer and use it in GitHub Desktop.
Turbolinks w/ Google ReCAPTCHA V3

Makes Google ReCAPTCHA V3 work with Turbolinks by persisting the badge element across visits.

License: CC0

Inspired by https://blog.bmonkeys.net/2019/using-recaptcha-v3-with-turbolinks

To use, paste the contents of snippet.html before your closing </head> tag.

<script type="text/javascript">
(function(d,w,c,b,m,k,h,i){
w.onGRLoad=function(){
n=d.createElement("div")
n.id=b
function s(){d.body.appendChild(n)}
s()
d.addEventListener("turbolinks:load",s)
h=grecaptcha.render(b,{size:'invisible',sitekey:k})
w[m]=function(l){l(h)}
for(i=0;i<c.length;i++){c[i](h)}
}
if(!w[m])w[m]=function(l){c.push(l)}
})(document,window,[],"gre-badge","mGrecaptchaReady","YOUR_GRECAPTCHA_SITE_KEY")
</script>
<script type="text/javascript" src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onGRLoad" defer></script>

Usage:

mGrecaptchaReady(function(h){
  grecaptcha.execute(key, {action: "ACTION_NAME"}).then((token) => {

  });
})

The badge will be persisted across page visits, you can call mGrecaptchaReady at any time after the script tag is placed (including before the page loads).

(function(siteKey){
var callbacks = [];
window.onGRLoad=function(){
var node = document.createElement("div")
node.id = "gre-badge"
function insertBadge(){document.body.appendChild(node)}
insertBadge()
document.addEventListener("turbolinks:load",insertBadge)
var handle = grecaptcha.render(b,{size:'invisible',sitekey:siteKey});
window.mGrecaptchaReady = function(cb){
cb(handle)
}
for (var i=0;i<callbacks.length;i++) {
callbacks[i](handle)
}
}
if (!window.mGrecaptchaReady) window.mGrecaptchaReady = function(l){
callbacks.push(l)
}
})("YOUR_GRECAPTCHA_SITE_KEY")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment