Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

facebook open graph crawler triggering json response in rails actions

For some reason the facebook crawler is triggering the json response in my rails actions. This causes the action to just return a json representation of the object, without the normal html markup + open graph tags. I have tested this with rails 3.2.6. I use the facebook open graph debugger to see what the scraper is seeing: http://developers.facebook.com/tools/debug.

The code is very simple. Imagine a simple "show" action for an object, for example a User. It ends with:

respond_to do |format|
  format.js { render :json => @this.to_json }
  format.html
end

The facebook crawler is triggering the format.js, which causes the open graph tags to not be rendered. Any ideas why this might happen or how to fix it? Thanks.

like image 795
Marc Avatar asked Jun 20 '12 03:06

Marc


2 Answers

Ok so Facebook sends an accepts header of

*/*

Since no specific format is requested, rails just goes down the respond_to block in order. If you list your js first in the respond_to block like below rails will respond to the facebook open crawler with JSON which will not work:

respond_to do |format|
  format.js { render :json => @this.to_json }
  format.html
end

Just switch the order so by default rails responds with HTML:

respond_to do |format|
  format.html
  format.js { render :json => @this.to_json }
end

I'm not sure why Facebook does not specify the format they are looking for... seems pretty idiotic to me. Hopefully this is helpful to somebody down the road.

like image 173
Marc Avatar answered Nov 01 '22 19:11

Marc


Check what HTTP request headers the Facebook crawler is sending – especially the Accept header.

Could well be that they send a value that let’s your application think it has to send something different then the normal HTML output.

like image 29
CBroe Avatar answered Nov 01 '22 20:11

CBroe