I’ve seen a lot of confusion about this lately, so I thought I’d make a quick writeup to explain how facebook does it. (I’ll also give a quick tip on how you can do it yourself.)
What Facebook Does
Facebook is in a unique position compared to many developers looking to set cross domain cookies: The user visits both facebook.com and the other website.
Facebook never actually sets cookies cross-domain, they only read cookies cross-domain. They set cookies on facebook.com when the user visits facebook.com and they set cookies on the other example.com (or any other website) when the user visits example.com.1
Doing things this way avoids all of the browser security issues because cookies that were already set when the user visited facebook.com can still be read when example.com loads facebook.com in an iframe. This is worth repeating: Cookies can be read in an iframe if they were set outside of the iframe.2
What about when the user is not logged into Facebook?
(This is how you can do it!)
If the user is not logged into Facebook when trying to use Facebook on example.com, then Facebook opens a popup window – not an iframe – to let the user log in.
A popup window has none of the cookie restrictions that iframes get; it can read and set cookies normally.
What about popup blockers?
Most popup blockers make a special exception for “intentional” popups – ones that occur as a direct result of a user’s click. When the user clicks the login button, the blocker allows the popup because the click indicates that the user wanted that popup.
Cross-domain communication
If you need to communicate between domains, modern browsers allow you to use postMessage to send data between web pages (although it doesn’t work with popups in Internet Explorer).
If you need to support older browsers, you can include the excellent easyXDM library for iframe-parent communication. You might need to combine a popup + one or more iframes in some situations.
An alternate method for of cross-domain cookies: flash
If you’re looking for a flash-based method of setting cross-domain cookies, or would otherwise like to avoid popups, you may want to check out my previous article, which includes source code: .swf for JavaScript cross-domain flash cookies
Notes
- Cookies are only set on example.com when using the using Facebook’s JavaScript SDK. When embedding Social plugins directly as an iframe, only facebook.com cookies are used.
- Safari sometimes prevents JavaScript from reading cookies in an iframe even if GET and POST requests to the server have full access to the cookies. Safari has several quirks like this, but generally behaves better with iframes if the user interacts with it.
Need a more advanced integration than what Facebook Social Plugins provide?
At Sociable Labs, our Intelligent Social PluginsTM increase social sharing by 15x and have shown a ~1% increase in sales. And the best part is that we do all of the hard work for you!