Facebook Javascript SDK with CoffeeScript
Introduction
This is a better and cleaner approach, for using the Facebook Javascript SDK:
- Javascript code is separated from the markup.
- The code is re-usable
How To Use
- Add environment variables
- Layout
- CoffeeScript
1: Environment Variables
If you are using forman, the variables will be loaded from the .env file.
Notice: Remove the .env file from production in the .gitignore file.
echo FACEBOOK_APP_ID=1234 >> .env
echo FACEBOOK_APP_SECRET=1234 >> .env
2: Layout
Add the environment variables into the application layout, as a data attributes.
With Jinja:
<div id="fb-root" data-app-id="{{ ENV['FACEBOOK_APP_ID'] }}"></div>
With Liquid:
<div id="fb-root" data-app-id="{{ ENV['FACEBOOK_APP_ID'] }}"></div>
With ERB:
<div id="fb-root" data-app-id="<%= ENV['FACEBOOK_APP_ID'] %>"></div>
With Jade:
div(id="fb-root", data-app-id= ENV['FACEBOOK_APP_ID'])
With HAML:
div{id="fb-root", data-app-id=ENV['FACEBOOK_APP_ID']}
Or in HTML
<div id="fb-root" data-app-id="1234"></div>
3. CoffeeScript
Notice: You can use channel.html file, instead of loading directly the Facebook JS files.
#
# You should add the Facebook App ID and the channel url (optional), in the #fb-root element, as a data- attribute:
# <div id="fb-root" data-app-id="<%= ENV['FACEBOOK_APP_ID'] %>" data-channel-url="<%= url_no_scheme('/channel.html') %>"></div>
#
window.fbAsyncInit = ->
FB.init
appId: document.getElementById("fb-root").getAttribute("data-app-id")
channelUrl: document.getElementById("fb-root").getAttribute("data-channel-url")
status: true,
cookie: true,
xfbml: true
FB.Event.subscribe('auth.login', (response) ->
window.location = window.location
)
FB.Canvas.setAutoGrow()
FB.getLoginStatus((data) ->
if (data.status == "connected")
uid = data.authResponse.userID
accessToken = data.authResponse.accessToken;
FB.api("/me", (data) ->
console.log("Hello #{data.name}")
)
else
if (response.status == "not_authorized")
# the user is logged in to Facebook,
# but has not authenticated your app
else
# the user isn't logged in to Facebook.
)
PageScript = document.getElementsByTagName("script")[0]
return if document.getElementById("FBScript")
FBScript = document.createElement("script")
FBScript.id = "FBScript"
FBScript.async = true
FBScript.src = "//connect.facebook.net/en_US/all.js"
PageScript.parentNode.insertBefore(FBScript, PageScript)
Gist for this code:
Written by Shavit
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside