Skip to content

Instantly share code, notes, and snippets.

@nbhartiya
Created March 25, 2015 22:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nbhartiya/51432bfbfc8a7563df97 to your computer and use it in GitHub Desktop.
Save nbhartiya/51432bfbfc8a7563df97 to your computer and use it in GitHub Desktop.
Javascript Widget Payload Script
# Name your class anything you want. Here, I call it Foo.
# Note that by writing out our code in its own class, we namespace it.
class Foo
constructor: ->
# Here we just set the host to your website, but you might want to add a little variable here
# to make it www.staging.yourwebsite.com when you're in the staging environment and localhost:3000
# when you're in the development environment.
@host = "www.your-website.com"
# Makes the base of xml requests http when we are testing on localhost.
@ajaxProtocol = "<%= Rails.env.development? ? "http:" : "https:" %>"
# This constructs a styleTag with your widget's stylesheet.
styleTag = document.createElement("link")
styleTag.rel = "stylesheet"
styleTag.type = "text/css"
# This is where your stylesheet can be found in our website.
# Be sure to make your stylesheet publicly accessible at this URL
styleTag.href = "//"+@host+"/assets/your-style-sheet.css"
styleTag.media = "all"
# Below, we add your styleTag to the head, enabling your widget to use any of the styles
# from your stylesheet.
document.getElementsByTagName("head")[0].appendChild styleTag
# Here, we identify our original embedder script
scriptTag = document.getElementById("unique-embedder-id")
# and get our client ID from it, assigning it to a variable.
# Remember when we set the data-client-id data attribute?
@client_id = scriptTag.getAttribute("data-client-id")
@getData()
getData: ->
# Gets the widget settings for a given company with a http request:
xmlhttp = new XMLHttpRequest()
xmlhttp.onreadystatechange = =>
if xmlhttp.readyState == 4
if xmlhttp.status == 200
# Assigns a callback function for when the settings have been retreived.
@onHaveSettings JSON.parse(xmlhttp.responseText)
xmlhttp.open "GET", @ajaxProtocol + '//' + @host + '/get-widget-settings-url/' + @client_id, true
xmlhttp.setRequestHeader "Accept", "application/json"
xmlhttp.send()
onHaveSettings: (response) ->
@settings = response['settings']
# Do whatever your widget is supposed to do based on company's settings. In our case,
# we're adding something to the DOM.
widget = @makeWidget()
# Checks if document has loaded, if not adds content loaded listener that then inserts our widget.
if document.getElementsByTagName('body')[0] == undefined
document.addEventListener "DOMContentLoaded", (event) =>
@putWidget widget
else
@putWidget widget
# This makes your widget show up on a single page app with turbolinks
document.addEventListener 'page:change', =>
@putWidget widget
makeWidget: ->
# Construct your widget however you like here using coffeescript (or javascript)
# It could add glitter to images on the page or whatever it might be
# You can also construct an iFrame here, if you wish
# In the end, return any divs you might want to attach to the page
# To be able to refer to it later, you might want to give it a uniqueWidgetId
# Injects widget into DOM body.
putWidget: (whatImInjecting) ->
document.getElementsByTagName('body')[0].appendChild(whatImInjecting)
@ourWidget = document.getElementById("yourUniqueWidgetId")
# Use below code to add event listeners for our widget
# The below allows us to do special things when someone clicks our widget
# Right now, we just track a click into our database
@ourWidget.addEventListener "touchstart", =>
@trackClickEvent
# Make our widget show up.
# You could also add a class to it from your stylesheet.
@ourWidget.setAttribute "style", "display: block;"
# Track analytics or save things to your database every time someone clicks your widget.
trackClickEvent: ->
click_event = {
widget_id: @settings["id"]
}
# Max an HTTP POST Request to our websites Widget Controller with the click information
xmlhttp = new XMLHttpRequest()
xmlhttp.open "POST", @ajaxProtocol + '//' + @host + '/widget_click_event', true
xmlhttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
xmlhttp.send(@serialize(click_event))
# A function to serialize our data before we send it across the internet
serialize: (obj, prefix) ->
str = []
for p of obj
if obj.hasOwnProperty(p)
k = (if prefix then prefix + "[" + p + "]" else p)
v = obj[p]
str.push (if typeof v is "object" then serialize(v, k) else encodeURIComponent(k) + "=" + encodeURIComponent(v))
str.join "&"
window.myWidget = new Foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment