ArticleslgStudy

science

JSONP

JSONP is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand JSONP rather than just read about it. In short: JSONP, or JSON-P (JSON with Padding), is a JavaScript technique for requesting data via the <script> HTML element. It was proposed by Bob Ippolito in 2005.

JSONP — main illustration
JSONP — illustration

Key takeaways

  • JSONP belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect JSONP to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of JSONP from memory before moving on to harder problems.

Reference excerpt

JSONP, or JSON-P (JSON with Padding), is a JavaScript technique for requesting data via the <script> HTML element. It was proposed by Bob Ippolito in 2005. JSONP enables sharing of data bypassing same-origin policy, which disallows running JavaScript code to read media DOM elements or XMLHttpRequest data fetched from outside the page's originating site. The originating site is indicated by a combination of URI scheme, hostname, and port number. JSONP requests are vulnerable to the data source replying with malicious code, which is why it has been replaced by CORS (cross-origin resource sharing, available since 2009) in modern applications.

Functionality The HTML <script> element is generally allowed to execute JavaScript code retrieved from foreign origins. Before the adoption of CORS, services replying with pure JSON data were not able to share data from foreign origins. For example, a CORS request to a foreign service http://server.example.com/Users/1234 may return a JSON response. However, an attempt to use the data across domains without CORS results in a JavaScript error. When http://server.example.com/Users/1234 is passed into the src attribute of a <script> tag, the browser will download the file, evaluate its contents, misinterpret the raw JSON data as a block, and throw a syntax error. Even if the raw JSON data were interpreted as a JavaScript object literal, object literals are inaccessible without a variable assignment. JSONP solves this by the client and server agreeing on a URL encoded query argument, conventionally jsonp or callback, which the client will use to define text that the server will prepend to its response, and wrap the JSON payload in parentheses resulting in a JavaScript document. When the encoded URL is passed into the src attribute of the <script> element, the client sends the JSONP request and the server response JavaScript document is loaded into the browser. Typically, this is used to call a function defined in the JavaScript environment and manipulate the JSON data in the response. An example JSONP request to http://server.example.com/Users/1234

In this example, the client defined parseResponse as the prepend text. The server response would be:

parseResponse({"Name": "Foo", "Id": 1234, "Rank": 7});

Here, parseResponse() is the "P" of JSONP—the "padding" around the pure JSON.

Script element injection JSONP makes sense only when used with a script element. For each new JSONP request, the browser must add a new <script> element, or reuse an existing one. The former option—adding a new script element—is done via dynamic DOM manipulation, and is known as script element injection. The <script> element is injected into the HTML DOM, with the URL of the desired JSONP endpoint set as the src attribute. This dynamic script element injection is usually done by a JavaScript helper library. jQuery and other frameworks have JSONP helper functions; there are also standalone options. An example of using jQuery to dynamically inject script element for a JSONP call looks like this:

After the element is injected, the browser evaluates the element, and performs an HTTP GET on the src URL, retrieving the content. Then the browser evaluates the return payload as JavaScript. This is typically a function invocation. In that way, the use of JSONP can allow browser pages to work around the same-origin policy via script element injection. The script runs within the scope of the including page and, as such, is still subject to cross-domain restrictions relative to the domain of the including page. This means that a web page cannot, for example, load a library hosted on another site via JSONP and then make XMLHttpRequest requests to that site (unless cross-origin resource sharing (CORS) is supported), although one could use such a library to make XMLHttpRequests to one's own site.

Security concerns

Untrusted third-party code Including script elements from remote servers allows the remote servers to inject any content into a website. If the remote servers have vulnerabilities that allow JavaScript injection, the page served from the original server is exposed to an increased risk. If an attacker can inject any JavaScript into the original web page, then that code can retrieve additional JavaScript from any domain, bypassing the same-origin policy. The Content Security Policy HTTP Header lets web sites tell web browsers which domain scripts may be included from. An effort was undertaken around 2011 to define a safer strict subset definition for JSONP that browsers would be able to enforce on script requests with a specific MIME type such as "application/json-p". If the response did not parse as strict JSONP, the browser could throw an error or just ignore the entire response. However, this approach was abandoned in favor of CORS, and the correct MIME type for JSONP remains application/javascript.

Whitespace differences JSONP carried the same problems as resolving JSON with eval(): both interpret the JSON text as JavaScript, which meant differences in handling U+2028 (Line Separator) and U+2029 (Paragraph Separator) from JSON proper. This made some JSON strings non-legal in JSONP; servers serving JSONP had to escape these characters prior to transmission. This issue has now been rectified in ES2019.

Callback name manipulation and reflected file download attack Unsanitized callback names may be used to pass malicious data to clients, bypassing the restrictions associated with application/json content type, as demonstrated in reflected file download (RFD) attack from 2014. Insecure JSONP endpoints can be also injected with malicious data.

Cross-site request forgery Naive deployments of JSONP are subject to cross-site request forgery (CSRF or XSRF) attacks. Because the HTML <script> element does not respect the same-origin policy in web browser implementations, a malicious page can request and obtain JSON data belonging to another site. This will allow the JSON-encoded data to be evaluated in the context of the malicious page, possibly divulging passwords or other sensitive data if the user is currently logged into the other site.

… excerpt ends here. Continue reading the full article.

Illustrations

JSONP: Graphical logo for JSONP
Graphical logo for JSONP

Worked examples

Example 1 — a first encounter with JSONP

Start with the simplest possible case. Write down what JSONP claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to JSONP before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about JSONP ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of JSONP

In research
JSONP appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses JSONP in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
JSONP is common in secondary-school and first-year university syllabi. It links to neighbouring topics Ajax (programming), JSON, so understanding it makes those chapters shorter.
In everyday life
Look for JSONP outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “JSONP” →

How to study JSONP in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what JSONP means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain JSONP out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is JSONP in simple terms?

JSONP, or JSON-P (JSON with Padding), is a JavaScript technique for requesting data via the <script> HTML element. It was proposed by Bob Ippolito in 2005.

Why does JSONP matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study JSONP?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on JSONP.

Tags

  • Ajax (programming)
  • JSON

Keep exploring