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).