Facebook JS SDK API – Post Image to Feed

Here’s a little snippet that will post an image to a user’s feed. It’s pretty handy as it shows all the components of using the Facebook Javascript SDK to post to the Facebook API.


function share_image(img_url, text) {
//Check to see if the user has authenticated the App.
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//If you want the user's Facebook ID or their access token, this is how you get them.
var uid = response.authResponse.userID;
var access_token = response.authResponse.accessToken;
do_api_share(access_token, img_url, text);
} else {
//If they haven't, call the FB.login method
FB.login(function(response) {
if (response.authResponse) {
//If you want the user's Facebook ID or their access token, this is how you get them.
var uid = response.authResponse.userID;
var access_token = response.authResponse.accessToken;
do_api_share(access_token, img_url, text);
} else {
alert("You must install the application to share your greeting.");
}
}, {scope: 'publish_stream'});
}
});
}
function do_api_share(at, img_url, text) {
FB.api("/me/photos", 'post', { message: text, url: img_url}, function(response) {
console.log(response);
});
}
//Calling the function
share_img("http://example.com/images/image-one.jpg", "Hi there!");

view raw

gistfile1.js

hosted with ❤ by GitHub

Facebook Set Auto Grow – A version that actually works

Edit October 25th, 2013

This is some updated code that I’ve found recently that works a bit better.


//The 100 value can be anything, Facebook will detect the height of the body element
FB.Canvas.setSize({height:100});

view raw

gistfile1.js

hosted with ❤ by GitHub

It can be triggered on load, or on an event. Theres no need for the setTimeout()… code any longer.


One the hard things about Facebook App development is debugging weird Facebook API issues.

One of them is the inconsistent use of the FB.Canvas Javascript methods. Particularly FB.Canvas.setAutoGrow and FB.Canvas.setSize. The documentation explains that (either or both?) can be used ad hoc to resize the app iframe. Well that’s not exactly the case, as neither work when called after the initial page load.

Although hacky, this solution actually works.


<div id="fb-root"></div>
<script type="text/javascript" src="//connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId: 'APPID', // App ID
channelUrl: '//example.com/channel.html', // Channel File
status: true,
cookie: true,
xfbml: true
});
FB.Canvas.setSize({height: 1200});
setTimeout("FB.Canvas.setAutoGrow()", 500);
</script>

view raw

gistfile1.phtml

hosted with ❤ by GitHub