breaking the cross domain barrier
DESCRIPTION
If you had to rank the best and worst moments of your JavaScript life, you’d probably rank reading “The Good Parts” up towards the top, and deep down at the bottom of the list would be the day that you found out that you couldn’t make cross-domain requests in the browser. This talk covers the hacks, tips, and tricks to leave the Same Origin Policy in the dust. So grab a cookie, pad your JSON, and learn how to communicate properly.TRANSCRIPT
Breaking The Cross Domain Breaking The Cross Domain BarrierBarrier
Alex SextonAlex Sexton
A Story...A Story...
AJAX is so nifty!AJAX is so nifty!We can do anything!We can do anything!FML :(FML :(
Same Origin PolicySame Origin PolicyApplies to XMLHTTPRequestsApplies to XMLHTTPRequestsStops hackers from getting our data!Stops hackers from getting our data!
Same Origin PolicySame Origin PolicyIt’s actually an important rule. You It’s actually an important rule. You wouldn’t want to have this happen:wouldn’t want to have this happen:
Same Origin PolicySame Origin PolicyIt’s actually an important rule. You It’s actually an important rule. You wouldn’t want to have this happen:wouldn’t want to have this happen:
YEA BUT WHAT IF...YEA BUT WHAT IF...I own both sites and I just want to make them I own both sites and I just want to make them talk?talk?The site I want information from says it’s okay?The site I want information from says it’s okay?I don’t give a shit?!I don’t give a shit?!
The SolutionThe Solution
Post Message.Post Message.
THE END.THE END.
kthnxbai.kthnxbai.
<RecordScratch.wav><RecordScratch.wav>
Browser Vendors have realized that there is a Browser Vendors have realized that there is a need for cross domain messaging.need for cross domain messaging.IE6 ruins your life again and again.IE6 ruins your life again and again.There is not a single solution that solves every There is not a single solution that solves every problem in every browser :(problem in every browser :(
Some OptionsSome OptionspostMessagepostMessageJSONPJSONPCORSCORSdocument.domain modsdocument.domain modswindow.name Transportwindow.name TransportServer-Side ProxyServer-Side ProxyCRAZY IFRAME STUFFCRAZY IFRAME STUFFMOARMOAR
Post MessagePost MessageJust pass messages between window objects!Just pass messages between window objects!It’s safe(ish) because both pages have to know about it.It’s safe(ish) because both pages have to know about it.
Post MessagePost MessageHandle the message event in the otherWindowHandle the message event in the otherWindow
Post MessagePost Message
Passing events along from one window to the Passing events along from one window to the otherotherInitializing the state of a new windowInitializing the state of a new windowSynchronizing two pagesSynchronizing two pagesMost things, but it’s not always practicalMost things, but it’s not always practical
What’s it good for?What’s it good for?
Post Message Works In...Post Message Works In...FF3+FF3+IE8+IE8+Chrome 1+Chrome 1+Safari 4+Safari 4+Kind of in Opera for a while but it’s a little Kind of in Opera for a while but it’s a little different but good enough probably so we’ll different but good enough probably so we’ll count itcount it
JSONPJSONP
JavaScript Object Notation with Padding. JavaScript Object Notation with Padding. (dumb I (dumb I know)know)
JSONENJSONENJavaScript Object Notation Except JavaScript Object Notation Except NotNot
**Formerly JSONP**Formerly JSONP
JSONJSON
A standard (mostly) created by the Crock.A standard (mostly) created by the Crock.A subset of JavaScript with some extra rulesA subset of JavaScript with some extra rulesNon-Executable - just for dataNon-Executable - just for data
JSONPJSONP
JavaScript...JavaScript...
JSONP - Why it’s specialJSONP - Why it’s special
The ‘P’The ‘P’<script> tags are not subject to the Same <script> tags are not subject to the Same Origin Policy Origin Policy (A (A totaltotal security flaw that will never change) security flaw that will never change)
How JSONP WorksHow JSONP WorksStep 1: You create a callback function that Step 1: You create a callback function that accepts some dataaccepts some data
How JSONP WorksHow JSONP WorksStep 2: Include a script with a hint of what your Step 2: Include a script with a hint of what your function is called.function is called.
hint-hinthint-hint
How JSONP WorksHow JSONP WorksStep 3: Output a script that calls the function Step 3: Output a script that calls the function and passes in the necessary data.and passes in the necessary data.
JSONP Is Good For...JSONP Is Good For...
Data PassingData PassingRESTful APIsRESTful APIs1-(way/time)-ish cross domain communication1-(way/time)-ish cross domain communicationHackingHacking
CORS | Tap the RockiesCORS | Tap the Rockies
Cross-Origin Resource Sharing (CORS) is a W3C Working Draft that defines how the browser and server must communicate when accessing sources across origins.
CORS - HOW?CORS - HOW?
CORS - HOW?CORS - HOW?Use it or lose itUse it or lose it
CORS - From the CORS - From the Server...Server...
CORS sends along an extra header:CORS sends along an extra header:
Your server must send back another, saying it’s Your server must send back another, saying it’s ok:ok:
CORS - CompatibilityCORS - Compatibility
IE 8+ (most of it, at least)IE 8+ (most of it, at least)FF 3.5+FF 3.5+Safari 4+Safari 4+ChromeChrome
Unrelated GraphUnrelated Graph
CORS - What’s it Good CORS - What’s it Good For?For?
Not working on 40% of the internetNot working on 40% of the internetCreating an extra http request (usually only Creating an extra http request (usually only once)once)Custom grouping optionsCustom grouping optionsFiner grain control over what’s accessible Finer grain control over what’s accessible Access-Control-Allow-Credentials: trueStraight Up. Cross Domain XHR Straight Up. Cross Domain XHR (yay!)(yay!)
Document.domain Document.domain HackzHackz
Good for allowing Cross Good for allowing Cross SubSubdomain window domain window accessaccess
Now the subdomain has the same permissions for Now the subdomain has the same permissions for accessaccessCan be very useful even if you don’t own the site, Can be very useful even if you don’t own the site, because subdomains can be cnamed to totally because subdomains can be cnamed to totally different webserversdifferent webserversWorks in all relevant browsersWorks in all relevant browsers
Window.nameWindow.name
HI! I’m Jerry the Window!HI! I’m Jerry the Window!
Window.nameWindow.nameSuperhacky but safer than jsonp!Superhacky but safer than jsonp!Works everywhere relevantWorks everywhere relevant
**This is obviously a little simplified**This is obviously a little simplified
Added to Dojo 2 years ago:Added to Dojo 2 years ago:http://bugs.dojotoolkit.org/ticket/6893
Server Side ProxiesServer Side ProxiesPretty simple concept, only slightly more Pretty simple concept, only slightly more difficult to implementdifficult to implement
mySitemySiteyourSiteyourSite
myServermyServerhttp://benalman.com/projects/php-simple-proxy/
Works everywhere XHR doesWorks everywhere XHR does
Crazy iFrame HacksCrazy iFrame HacksA parent window can’t A parent window can’t readread just about just about anything from a child window (iframe) that is anything from a child window (iframe) that is on a different domain.on a different domain.A parent window can traverse any known A parent window can traverse any known elements in an iframe though.elements in an iframe though.A parent window can A parent window can setset properties on the properties on the iframe.iframe.
FACTSFACTS
Crazy iFrame HacksCrazy iFrame HacksA window can read and write properties of an iframe A window can read and write properties of an iframe if it’s on the same domain - EVEN IF it’s inside of if it’s on the same domain - EVEN IF it’s inside of another iframe that isn’t on the same domain!another iframe that isn’t on the same domain!
a.coma.com
b.comb.coma.coma.com
Crazy iFrame HacksCrazy iFrame HacksIf B wants to talk to AIf B wants to talk to A
a.coma.com
b.comb.coma.coma.com
Change the url hash on the innermost iframe to the Change the url hash on the innermost iframe to the messagemessage
/#secret/#secret
Crazy iFrame HacksCrazy iFrame HacksIf B wants to talk to AIf B wants to talk to A
a.coma.com
b.comb.coma.coma.com
Have the top level frame read the message on the Have the top level frame read the message on the hashhash
/#secret/#secret
Crazy iFrame HacksCrazy iFrame Hacks
Poll for hashchange the entire timePoll for hashchange the entire timeSet up iframes to destroy themselves after Set up iframes to destroy themselves after each message and just wait for the load eventeach message and just wait for the load eventResize the iframe on change, then attach an Resize the iframe on change, then attach an event handler on the resize event that checks event handler on the resize event that checks for new datafor new data
How to know when to receive How to know when to receive datadata
Fast (where it works)Fast (where it works)
Crazy iFrame HacksCrazy iFrame HacksWorks at varying levels of success via some Works at varying levels of success via some slightly different methods in all relevant slightly different methods in all relevant browsersbrowsersUnfortunately often our best choice for Unfortunately often our best choice for something that works everywheresomething that works everywhere
Best of both worlds?Best of both worlds?EasyXDMEasyXDM
A library that will use postMessage first and then a series of A library that will use postMessage first and then a series of different techniques based on which browser you use, butdifferent techniques based on which browser you use, butwith normalized syntax.with normalized syntax.
http://easyxdm.net/
Best of Both Worlds?Best of Both Worlds?flXHR / Flash + your own fallbackflXHR / Flash + your own fallback
http://flxhr.flensed.com/
What about cookies?What about cookies?Cookies are insanely easy to Cookies are insanely easy to stealsteal, err.. I mean , err.. I mean share, across domains with these techniques.share, across domains with these techniques.With the exception of Safari, cookies are passed With the exception of Safari, cookies are passed from the server along with script includes and iframe from the server along with script includes and iframe injection. (You might need some P3P headers in IE)injection. (You might need some P3P headers in IE)
What about cookies in What about cookies in Safari?Safari?
Safari doesn’t send cookies along in scripts and Safari doesn’t send cookies along in scripts and iframes, so there’s nothing to send to the iframes, so there’s nothing to send to the parent.parent.Unless you ask nicely...Unless you ask nicely...
What about cookies in What about cookies in Safari?Safari?If we post to an iframe it will thank us by sending If we post to an iframe it will thank us by sending
cookiescookies
http://anantgarg.com/2010/02/18/cross-domain-cookies-in-safari/http://anantgarg.com/2010/02/18/cross-domain-cookies-in-safari/
Why Cookies?Why Cookies?If I had a network of sites that I wanted to track you If I had a network of sites that I wanted to track you across, it would be easy for me maintain a central across, it would be easy for me maintain a central cookie and check for it on every site that you enter cookie and check for it on every site that you enter that contains my code. that contains my code. (<cough>advertisers</cough>)(<cough>advertisers</cough>)
TotallyNotTrackingYou.comTotallyNotTrackingYou.com
Other SitesOther Sites
Holds your unique cookieHolds your unique cookie
LessonsLessonsWith great cross domain communication With great cross domain communication techniques come great cross domain security techniques come great cross domain security holesholesSafe and FUN cross-domain communication is Safe and FUN cross-domain communication is possiblepossiblePaul Irish Paul Irish hateshates cold-cuts , cold-cuts , seriouslyseriously
Thanks!Thanks!Alex SextonAlex SextonAlexSexton [at] gmail [dot] comAlexSexton [at] gmail [dot] com@SlexAxton@SlexAxtonhttp://yayQuery.comhttp://yayQuery.com
Special Thanks toSpecial Thanks to: yayQuery Peeps, : yayQuery Peeps, BazaarVoice, Aaron Dixon, Shawn Smith, BazaarVoice, Aaron Dixon, Shawn Smith, EasyXDM, flXHR, Mozilla MDCEasyXDM, flXHR, Mozilla MDC