Friday, February 12, 2010


How to use FB.Connect.streamPublish()



Please note: This guide is dated and I would recommend using the new Facebook Javascript API for this functionality. Check out this guide on the Facebook Developer site.

I have spent countless hours searching the Developer forums and reading over the wiki and haven't found a single, all-encompassing source that describes how to properly use FB.Connect.streamPublish(). This article is geared towards iFrame applications, but the same methods are used for external web sites using Facebook Connect. Also, if you own a web design company, please take a minute and add it to The Web Company Directory for free!

First, it is extremely important to have the proper connect settings.


1. Connect URL


Click the Connect tab in your application's settings, and set the Connect URL to your site's address with no ending / (i.e. http://www.ugadevelopers.com/frmatch).

(iFrame apps: Also ensure that you have set your Bookmark URL equal to your Canvas URL: http://apps.facebook.com/<yourapp>)


2. Cross-Domain Communication Channel


Next, you need to set up a cross-domain communcation channel so your Connect calls can send/receive info to FB. Enter this into a file and save it as xd_receiver.htm:



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cross-Domain Receiver Page</title>
</head>
<body>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js?2" type="text/javascript"></script>
</body>
</html>



Save this file into the same directory as your application. I saved it in the /frmatch/ directory.


3. Set up your page to make Connect calls.


In the file you are trying to make Connect calls in, you need the following code segments in the correct place:

3a. <html> tag


First, you have to include some special parameters in your <html> tag to let the browser know how to render the XML:


<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">



3b. FeatureLoader Javascript


Next, you need to include the FeatureLoader Javascript, which is responsible for loading the features necessary to make certain calls. (Note: You must place this line directly below the <body> tag!)



<body>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>



3c. streamPublish() call


Finally, we are ready to make the streamPublish() call. Here is a barebones script to test and make sure that everything is working correctly (don't forget to change to your api key):


<script type="text/javascript">

function publish() {
FB_RequireFeatures(["Connect"], function() {
FB.init('xxxxxxxxxx', 'xd_receiver.htm');
FB.ensureInit(function() {
FB.Connect.streamPublish();
});
});
}

</script>

<p>Stream Publish Test</p>
<a href="#" onclick="publish(); return false;">Post a story</a>



3d. Pop up dialog on window load


To pop up the feed dialog when the page loads (i.e. user lands on a high scores page and you present them a dialog to publish their high score), simply add the following script after the one above:


<script type="text/javascript">
window.onload = publish;
</script>


3e. streamPublish() with additional content


I assume most people want to display some content that is relevant to their app. Here is an example of attaching an image and a message to the post:



<script type="text/javascript">

function publish() {

var attachment = {
'name':'FriendMatch',
'href':'http://apps.facebook.com/frmatch',
'caption':'{*actor*} is playing FriendMatch!',
'media':[{
'type':'image',
'src':'http://www.ugadevelopers.com/frmatch/tile.png',
'href':'http://apps.facebook.com/frmatch/'
}]};

var action_links = [{'text':'Match Friends','href':'http://apps.facebook.com/frmatch'}];

FB_RequireFeatures(["Connect"], function() {

FB.init('xxxxxxxxxx', 'xd_receiver.htm');

FB.ensureInit(function() {

FB.Connect.streamPublish('', attachment, action_links);

});

});

}

</script>


I hope this helps some people. FB's documentation of setting up this process is spotty at best!

Share







96 comments:

  1. Great article. Hope you write more of those, you'll become my bible.

    ReplyDelete
  2. Thanks for this! I was looking everywhere for something like this. It would be great if you wrote also about the Share with friends for iframe apps. Thanks again!

    ReplyDelete
  3. Dude you have anything about XBFML fb.request-form? Thanks

    ReplyDelete
  4. What does the following do in the caption for the attachment?? Is it a fb var or something you are doing? If it is a fb var where did you find it? Thanks for all the info, it helped a ton!!!!

    {*actor*}

    ReplyDelete
  5. {*actor*} is replaced by the name of the target.

    ReplyDelete
  6. doesn't work. i get an error that there should be no body tags in the canvas.

    ReplyDelete
  7. Then you are using FBML instead of iFrame.

    ReplyDelete
  8. yeah, i got it working now. i just changed it to iframe. thanks :) this post helped a lot!

    ReplyDelete
  9. Hi Michael,

    I tried many ways to perform this. Followed all your tips, and I still can't use the streamPublish. I've checked the code, the flow passes through the function, but nothing happens, even a warning/error on the Firebug console.

    Any thoughs ?

    ReplyDelete
  10. thank's for your contribution, is very effective and functional, i can't donate money,... but i'm going to click below, TnK'S.

    ReplyDelete
  11. Michael,
    Everything works fine until I attempt to post to the wall of an event. I get a message that tells me that I am not authorize to do this: "An invalid target was specified...".

    I use the event id as the target_id in the call.

    Have you tried doing this? Do you know if it works?

    ReplyDelete
  12. In Step 1, you say to set the Connect URL to your site's address with no ending /. However, when I try that I get the error "Validation failed. Connect URL must point to a directory (i.e., end with a "/") or a dynamic page (i.e., have a "?" somewhere)."

    Were you able to create a Connect URL without the trailing slash?

    ReplyDelete
  13. Actually, I think it is O.K. to use a trailing slash after reading a few more articles.

    ReplyDelete
  14. please create an article for $fb->api_client->stream_publish in php

    ReplyDelete
  15. Thanks A LOT! Finally I got all the pieces for this to work, the Connect URL setting was essentially what I was missing... Aarrgh... ;-)

    ReplyDelete
  16. you have a typo in your example 3d:

    'href':'http://apps.facebook.com/frmatch/'
    }];

    should be }]};

    caused me some minor aggravation :P Other than that, thank you for synthesizing everything.

    ReplyDelete
  17. there is an error in your publish() function code...
    }]; this line of code needs an additional } ...thanks for your code...its a rare & nice one....

    ReplyDelete
  18. thanks for this, always appreciated when the full page rather than snippets are posted. there is that typo arun pointed out, but it was easy to spot.

    ReplyDelete
  19. Thanks for informing me of the error; I have updated the code.

    ReplyDelete
  20. Hi ,
    I really thankful to u.my prayers always with you

    ReplyDelete
  21. This worked extremely well for me. Thanks! It's a fantastic help to have such a simple, clear example .. especially given all the %*(#! out there.

    ReplyDelete
  22. How to put this code inside echo (php) ?

    Mine always error..

    Thanks

    ReplyDelete
  23. Thank you very much. You helped me a lot...
    I was searching for days...

    ReplyDelete
  24. After searching for days, this is the best and most simple explanation I have read. It simply works!!! Thanks!

    ReplyDelete
  25. Thanks a lot!!! Really working

    ReplyDelete
  26. Thanks! It works like a charm!

    ReplyDelete
  27. Wow... you saved my life ! 3 hours spent before finding your article... Thanks a lot.

    ReplyDelete
  28. Any ideas on how to get this to work in a tabbed IFrame applications?

    ReplyDelete
  29. Many thanks, this was very helpful!

    ReplyDelete
  30. You're a lifesaver ;-)

    ReplyDelete
  31. On a tabbed iFrame application you can access the method by using the 'Facebook' object (e.g. 'Facebook.stremPublish()')

    I was just able to figured out how to make it work after looking on Firebug for all the variables/objects/methods that start with my appID (eg: a123456789_MethodNameGoesHere ) - I couldn't find anywhere on the documentation how to do it..

    since facebook escapes all the vars you don't have access to the 'FB.Connect' object inside a tab.. (even thought it exists on the HTML if you check on Firebug..) Facebook wrongly replaces it to 'a123456789_FB.Connect'.

    The Facebook API sucks and the documentation sucks 10x more.. it's really frustrating..

    ReplyDelete
  32. WoW!! Thank you Michael Plunkett!
    I've been searching on how to do this for 7 hours, and your article here works in the very first try!
    I hope you will keep writing such wonderful articles about FB App Development.
    Really, thanks!!

    ReplyDelete
  33. Great! Thank you a lot!!

    ReplyDelete
  34. Thanks a lot! It's hard to find this info now.

    ReplyDelete
  35. How do you change "Publish Score"?

    ReplyDelete
  36. You're a lifesaver ! Thanks man :)

    ReplyDelete
  37. Has anyone gotten this working on a tabbed iFrame? Using the publish() code the way it's written it does nothing, not even an error. But if I change to Facebook.streamPublish() as was suggested above, I get the error "Facebook is not defined"

    ReplyDelete
  38. Nevermind, I got this working now. My directory structure is quite complex and it turns out I just had the xd_receiver.htm in the wrong place, or more specifically I will have two facebook apps and had put the file in the directory for one but not the other :( Thanks so much for this tutorial, I only wish I had found it sooner!

    ReplyDelete
  39. how can i set the auto publish ? i try to set true but the dialog box continue to appears

    ReplyDelete
  40. Hey,
    Thanks Michael have been searching through the developer wiki for days looking for something like this. Also thanks to the one on the invite I was able to compare my code to your and find a bug also.
    Thad

    ReplyDelete
  41. Thanx buddy this article is fantastic !!!!!!..
    Thanx a lot

    ReplyDelete
  42. Adding "user_message_prompt" allows you to change the default "What's on your mind?" header.

    ReplyDelete
  43. I have a problem. Only application developers can see what is posted on the wall, and other users can't. Did anyone have similar problem?

    ReplyDelete
  44. I have found a reason. :-)
    Sandbox mode must be off.

    ReplyDelete
  45. Is there a way to make a part of the caption as a link..like
    'Get this from xyz.com' (need to make xyz.com as a link).

    ReplyDelete
  46. Thanks a bunch man!

    ReplyDelete
  47. how can i break line on caption parameter

    ReplyDelete
  48. This was a great tutorial! Worked like a charm. Thanks man.

    ReplyDelete
  49. Thanks,
    but how to make/write script like FB.Connect.streamPublish() for FBML Render Method.

    ReplyDelete
  50. yo rock - thanks for this!

    ReplyDelete
  51. for me doesn't work

    My connect url need to have index.php?p=home parameter... how can i resolve it?

    I need solution asap

    I'm sorry for my english

    ReplyDelete
  52. thanks a ton, buddy

    ReplyDelete
  53. Thank you so much. I had most of it working on my own but there was one variable missing that slowed and glitched up the call. I read this article, fixed it and it's working great now. Thanks for contributing!

    ReplyDelete
  54. Thanks for the info. I finally created my apps.
    http://apps.facebook.com/sendymnow/?_fb_fromhash=dfa0888b7b8e371cdf7d0a5b422f304a

    ReplyDelete
  55. THANKS. YOU ARE A LIFE SAVER.

    ReplyDelete
  56. Its working! Its working! I spent so much time trying to figure this one out. I spent a few days trying to fix this. Thanks a lot!!!!!!!!!!!!!!!!!!!!

    :D XD :)

    ReplyDelete
  57. So this took me a good long while. Stream.Publish will use a pop-up if the app is "disconnected", another words the user hasn't authorized the app. You can try this a number of ways on FB's RELL App.

    http://fbrell.com/fb.ui/stream.publish

    Starts to make a little sense after a while, that, or after five hours I've started drinking the Zuckerberg koolaid. In any case, the pop-ups sucks because it will be blocked unless you call it just right. So, it's probably better in you're going to use Stream.publish at all to get your app connected, so you don't have to deal with it.

    ReplyDelete
  58. Great Post thanks a lot
    workt in minutes like a sharm nicest post on Fbstream.
    Just one missing how you post as admin to a page instead to profile ?
    with target_id i get a error .
    But thans one more time
    @Metacowboy

    ReplyDelete
  59. amazing post man

    ReplyDelete
  60. hi, great work by the way...
    i got everything workin in a jiffy. Anyways, once i post to my wall, when i click on link on my fb profile it opens in the same new window. How can i make it open in a new window?..Tried adding 'target': '_blank' to the properties like this 'properties': { 'category': { 'text': 'Women\'s media', 'href': '', 'target': '_blank'} },
    but doesn't help.

    Would really appreciate your help here..

    ReplyDelete
  61. I don' know how to add extended permission into request for permission popup as soon as login first times. I want to use FB.Connect.streamPublish because i can custom auto_publsih is true. Is there any way?
    Thanks

    ReplyDelete
  62. Hi! Thanks for your post. It looks like it will work this way, however I get this error when loading the page:
    "Permission denied for (document.domain has not been set) to call method Location.toString on"

    Can you tell me what I'm doing wrong? Thanks.

    ReplyDelete
  63. THANK YOU!

    But, God I was fighting with it for days!

    BE AWARED:
    NOT ADD 'www' before 'http://' in your Connect URL or Canvas URL! Finnaly i tried http://mydomain.pl/name/ for both and IT WORKS! :)

    ReplyDelete
  64. This comment has been removed by the author.

    ReplyDelete
  65. wow, this is the first start-to-finish tutorial that actually worked. The official FaceBook documentation is hopelessly inadequate; FaceBook should definitely hire you. Thanks a bunch.

    ReplyDelete
  66. Thanks buddy. It work just fine at the first shot. Now I don't want the pop up but want my application to auto publish a hard coded message. How can I achieve this?

    ReplyDelete
  67. Thank MICHAEL PLUNKETT
    It work fine too but sometime ,It show like this
    Error Message: Param "action_links" must be a JSON-encoded string.

    Do you have any suggest me ?
    Thank in advance

    ReplyDelete
  68. HI everyone..... I need the light pop-up same as facebook one... the above code gives me popup window... I dont need popup window ... I need light pop up as Facebook... Can any body help me out ASAP...
    Thanks in advance.....

    ReplyDelete
  69. It's lightweight and simplified. Thanks for sharing the knowledge.

    ReplyDelete
  70. Looking forward to giving this a go on my site. Thanks for explaining it better than every where I have searched so far. Cheers!

    ReplyDelete
  71. Since yesterday, Oct 8, 2010, I'm getting the same error as Seduire.

    API Error Code: 100
    API Error Description: Invalid parameter
    Error Message: Param "action_links" must be a JSON-encoded string.

    Does anyone know what Facebook has changed? My app was working normally before.

    ReplyDelete
  72. sbudlong :

    I have noticed you have posted this same issue around a few forums. I cannot tell you why this is happening (most likely something broken in Facebook which will get fixed soon I am sure). A temporary workaround is to remove the action_links argument object and all args after i.e;

    Facebook.streamPublish(
    'message in here', attachmentObj
    );

    This will work, of course; It assumes you don't need to pass action_links, target_id, user_message_prompt, etc...

    Hope this helps you for the while

    ReplyDelete
  73. Thanks buddy. I don't have money to donate u, but click the ads is what i can do, LOL.

    ReplyDelete
  74. Doesn't work for me. Your demo content works from my app login but doesn't work when I put it on a Fan page Tab. Is iframe impossible there? I even tried the "Hello World" example in its basic form and yeah, that works but it doesnt' work on a Fan page either. Seems it never loads up anything from my remote site when it's on a Fan page tab.

    ReplyDelete
  75. thank you! thank you!!! that's not what i need but you gave me some ligth!!
    THANKS A LOT MEN!!!

    ReplyDelete
  76. key point to this entire post...

    make sure that script for the FB loader is *IMMEDIATELY* after body tag. ;)

    thanks - it helped me debug/successfully complete the iframe sizing issue... *even the FB docs* didn't make this discerning point... 2 days could'a been saved. :)

    not to mention the hundreds of hair strands that could'a been saved, having read this post first :)

    well done! thanks

    ReplyDelete
  77. k, I previously posted a jan 31 response, but wanted to follow-up again - tho this works, if you're going to be using xfbml + new .js sdk then you'll not be using fb at all....

    just fyi.

    ReplyDelete
  78. Hey there,very nice guide I must say !
    I just wanted to ask,is it possible to edit the popup window height and width...and how ??

    ReplyDelete
  79. You just saved my day, thanks a lot.....

    ReplyDelete
  80. is this compatible with the facebook tab manager for wordpress?... because i am failing to get this to work... :(

    ReplyDelete
  81. WRONGNUMBER - Not sure I don't have any experience with that, sorry.

    ReplyDelete
  82. thanks a lot, just what i needed.

    ReplyDelete
  83. Nice one.Very valuable information.
    Keep sharing and updating your blog with new topics.

    ReplyDelete