Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class AppOS.Component.Recaptcha3 extends AppOS.Component
name: "recaptcha"
API_URL: "https://www.google.com/recaptcha/api.js?onload=%callback&render=explicit"
API_KEY: "MY_PUBLIC_SITEKEY"
init: ->
@pending = []
@apiState = "unloaded"
# init event
$(document).on "recaptcha:init", (ev) => @initRecaptcha()
# global callback for API
window.AppOSRecaptchaAPILoaded = =>
@apiState = "loaded" if @apiState == "loading"
document.grecaptchaHandle = grecaptcha.render 'grecaptcha-badge',
sitekey: @API_KEY
badge: 'inline'
size: 'invisible'
@_execute(@pending.shift()) while @pending.length
# called via turbolinks:load (which is called for initial load and subsequent navigations)
pageLoad: -> $(document).trigger("recaptcha:init")
initRecaptcha: () ->
if @apiState == "unloaded"
@apiState = "loading"
@pending.push()
$.getScript(@API_URL.replace("%callback", "AppOSRecaptchaAPILoaded")).fail =>
@apiState = "blocked"
window.AppOSRecaptchaAPILoaded()
else if @apiState == "loading"
@pending.push()
else
@_execute()
_execute: (el) ->
if @apiState == "blocked"
$("#grecaptcha-badge").html("<strong>Google ReCaptcha got blocked by your browser, form submission is not possible! Disable content blocking for this site.</strong>")
return
grecaptcha.execute(document.grecaptchaHandle).then (token) -> console.log "executed", token
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.