Auto-resize a Facebook Application iframe

Huzzah! The end of another busy week full of lots of (mostly) enjoyable work; mainly involving Facebook in some way or another. Lots of clients have really jumped on Facebook recently and the demand for their own “apps” has increased dramatically.

Setting up an app inside an iframe is easy, but one thing you don’t want is scroll bars as they look damn ugly! You can set an iframes height using the setSize() method but what about if the iframe varies in size between pages and user interactions (accordions, show / hides etc); you need some way of automating this. Luckily Facebook has already added this functionality to the JavaScript SDK, you just need to enable it. The API docs for this seemed a little flaky, with quite a few comments from people who couldn’t get it to work; so here’s a solution that worked for me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div id="fb-root"></div>
<script type="text/javascript">
    window.fbAsyncInit = function() {
        //Your app details here
        FB.init({appId: 'your_app_id', status: true, cookie: true, xfbml: true});
        //Resize the iframe when needed
        FB.Canvas.setAutoResize();
    };

    //Load the SDK asynchronously
    (function() {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +
          '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
    }());
</script>

Copy and paste this into the body of your iframe and you’re halfway there. The last thing to do is check your application settings, under one of the advanced settings pages you will find an auto resize check box that you will need to enable (sorry I can’t remember exactly which page!). Once enabled your iframe should resize automatically depending on the page content. There are a few parameters you can tweak with the setAutoResize() method, they are documented here. Fingers crossed it works for you too!

Important Update: One thing I just noticed with the code, it didn’t work in IE! Not great. Luckily there was a quick fix. Change script type=”application/javascript” to type=”text/javascript”. IE doesn’t like application/javascript!

Loading

Webmentions