Skip to content

Instantly share code, notes, and snippets.

@2called-chaos
Last active March 2, 2019 15:48
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 2called-chaos/da02da3af297d4e39715ddfdd81ce7d4 to your computer and use it in GitHub Desktop.
Save 2called-chaos/da02da3af297d4e39715ddfdd81ce7d4 to your computer and use it in GitHub Desktop.
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