Cross-Site Scripting with JSONP
While JavaScript's XmlHttpRequest object does not allow you to
load data from outside of the page's current domain because of the
same origin policy, it turns out that SCRIPT tags are not subject to the "same
origin" policy. Consequently, an informal standard known as JSONP has
been developed that allows data to be cross-domain loaded. As you
might imagine, it is this very capability that empowers web
applications[13] to mash up data from multiple
sources and present it in a single coherent application.
JSONP Primer
Like anything else, JSONP sounds a bit mysterious at first,
but it is pretty simple once you understand it. To introduce the
concept, imagine that a SCRIPT
tag is dynamically created and appended to the HEAD of a page that was originally loaded
from http://oreilly.com. The interesting twist
comes in with the source of the tag: instead of loading from the
oreilly.com domain, it's
perfectly free to load from any domain, say http://example.com?id=23. Using JavaScript, the
operation so far is simple:
e = document.createElement("SCRIPT");
e.src="http://example.com?id=23";
e.type="text/javascript";
document.getElementsByTagName("HEAD")[0].appendChild(e);Although the SCRIPT tag
normally implies that you are loading an actual script, you can
actually return any kind of content you'd like, including JSON
objects. There's just one problem with that—the objects would just
get appended to the HEAD of the page and nothing interesting would happen (except ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access