Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Consuming Third Party Data With JSONP

Bruno Genaro
September 08, 2015

Consuming Third Party Data With JSONP

In this talk, Bruno Genero(@bfgenaro) will go through how to request data from a server in a different domain and not to worry about the “Same-origin policy” using the JSONP technique.

Bruno Genaro

September 08, 2015
Tweet

More Decks by Bruno Genaro

Other Decks in Technology

Transcript

  1. WHAT IS THIS PRESENTATION ABOUT? • Same-Origin Policy • What

    is JSONP? • JSONP vs CORS • When and why? • JSONP Callback • Other options
  2. For security reasons, web browsers prevent what are called “cross-

    origin” or “cross-site” requests from one domain to another SAME-ORIGIN POLICY “… the same-origin policy is an important concept in the web application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin.” Wikipedia
  3. JSON with Padding JSONP is a way to fetch JSON

    data from a different domain. It takes advantage of the fact that browsers do not enforce the same-origin policy on <script> tags. WHAT IS JSONP? - Take a pure JSON, make it a function call, then eval it in the browser - Same-Origin Policy does NOT apply to resource loading (script tags) - Yes, it’s a hack!
  4. - Support to old browsers (IE<=7, Opera<12, or Firefox<3.5) -

    Only GET - Easy jQuery integration - Partial or no control on the server side - Most APIs have JSONP support - Cross-Origin Resource Sharing - IE8 and IE9 issues - Read/write (e.g. full REST or just POST/GET) - More Secure - Full control on the server side - Know the domains you want to enable JSONP VS CORS JSONP CORS WHEN AND WHY?
  5. - This callback arrangement between you and the server is

    really the whole trick to JSONP. The function padding around JSON data is why it’s called JSONP. - In order to retrieve the API answer from the newly included JavaScript code, jQuery automatically appends a callback argument to your URL (for example &callback=functionCallback ) which must be called by the JavaScript code that your API generates. - As long as a callback parameter is provided to the getJSON method, jQuery will consider the request JSONP. (https://github.com/jquery/jquery/blob/1.4.4/src/ ajax.js#L224) JSONP CALLBACK