How to use AdSense in a Facebook app
Tuesday, June 17th, 2008
One of YieldBuild’s engineers, Tim Connor, has written this short guide on how to install AdSense in your Facebook app.
As a way to secure 3rd-party application development, but still allow for Web 2.0/Ajax style apps, Facebook came up with their own subset of Javascript: FBJS. Basically as an app developer you write your JavaScript as FBJS and when you serve the FBML over to Facebook, they parse it, checking for security violations, invalid syntax, etc. They then wrap it in a unique namespace—to not interfere with any of the other Javascript on the page—by prepending a random string of digits to all the variables and function names.
The end result of this is that you cannot access objects such as window, document, or any other JS built-in directly, since they will be serving up, as a hypothetical example, 123456789_window instead of window. Instead, they have created wrappers for many of the useful functions, such as a Ajax, object, and custom versions of many of the common DOM operations. While this is not too onerous if you are doing green-field development, it does not lend itself well to simply recycling either a large Javascript application, or more importantly, a 3rd party Javascript file you have no direct control over, such as AdSense.
Thus, to run AdSense in a FBML app, you need to insert a iframe for each ad (for example, a fb:iframe tag), and have a simple page with just the basic HTML/body/etc tags, and the AdSense script tag. This sub-frame will be served directly from your domain, so have no script-level access to the upper level facebook page. Luckily, for tasks such as having the iframe resize to the height of the ad, Facebook allows some crossdomain-crossframe workarounds.
Beware, though, if you are trying to dynamically generate your AdSense iframes with FBJS (which YieldBuild does), it is going to requires some fancy footwork to work within the restrictions and undocumented features of FBJS. Things such as creating DOM obects, setting name and id and src are all possible, but not explained well in the documentation. I suggest firing up Firebug and grabbing a reference to a dom node to examine what functions are available that meet your specific needs. You may eventually run up against hard-limits, though, such as not being able to dynamically create crossbrowser resizable iframes (the way Facebook handles the crossframe communication currently requires the iframe to exist, with the same name, at load time).
Or you could just use YieldBuild and let us worry about all those parts. ![]()

