Javascript inside a Facebook profile tab
Posted: March 25th, 2010 | Author: Pierre Olivier Martel | Filed under: Facebook, Javascript, Rails | View CommentsDeveloping a Facebook application that runs in a profile tab can be a real pain in the neck. As stated on the Facebook developer wiki, one of the many constrains developing a Facebook tab forbids the use of external javascript files. This means you have to inline your javascript in a script tag in order to be processed by the Facebook FBML parser.
This is a real problem if you have javascript files for your Facebook application and wish to keep your code DRY. Here is the solution I came up with using Ruby on Rails and Facebooker :
# ApplicationController.rb
helper_method :request_is_facebook_tab? # Make the facebooker method available in views and helpers
# Application.fbml.erb
<%= render :partial => 'facebook/fb_js' %>
# _fb_js.fbml.erb
<% if request_is_facebook_tab? %>
<%= javascript_tag output_js_files_content("Utility.js", "FBjqRY.min.js", "application-fb.js") %>
<% else %>
<%= javascript_include_tag "Utility.js", "FBjqRY.min.js", "application-fb.js" %>
<% end %>
# facebook_helper.rb
def output_js_files_content(*files)
output = files.collect { |f| IO.read(File.join(RAILS_ROOT, 'public', 'javascripts', f)) }
output.join("\n")
end
This code will detect wether or not the facebook application is running inside a profile tab. If so, instead of generating an external javascript tag, an helper method is called to dump all the content of javascript files inside a script tag.
This solution lets keep your javascript where it belongs (inside .js files) and keep your code DRY when dealing with profile tabs limitation.
Passionate web developer living in Montreal and hacking in Ruby on Rails available for contracts and freelance work.