JSON JSONP

JSONP (JSON with Padding)

Requesting files directly from a completely different domain can cause massive security issues.

Due to strict browser policies (CORS), cross-domain XMLHttpRequest and Fetch calls are often blocked by default.

JSONP is a historical method created specifically to bypass this severe cross-domain restriction!


How Does JSONP Work?

While browsers block cross-domain HTTP requests, they do not block cross-domain <script> tags.

JSONP exploits this loophole by requesting the external data as a functional JavaScript script!

Instead of returning a plain JSON string, the server returns the JSON data wrapped inside a JavaScript function call.


The JSONP Callback

When the external script loads, it immediately executes the wrapper function (the "Padding").

You must define this function locally on your webpage before making the request.

Once executed, the function perfectly captures the JSON payload passed as its primary argument!

JSONP Architecture Example:

<!-- 1. Define the callback function first -->
<script>
function myCallback(response) {
  // 'response' contains the safely returned JSON data!
  console.log("JSONP Payload:", response.name);
}
</script>

<!-- 2. Make the cross-domain request via script tag --> <script src="https://example.com/api.php?callback=myCallback"></script>

<!-- The server actually responds with this literal text: myCallback({ "name": "John Doe", "age": 30 }); -->


Modern Alternatives (CORS)

Today, JSONP is largely considered a legacy technology and is rarely used in modern applications.

Modern web servers simply use CORS (Cross-Origin Resource Sharing) HTTP headers.

By enabling CORS on the server, you can use the standard Fetch API securely without relying on JSONP hacks.


Exercise 1 of 2

?

What does JSONP stand for?

Exercise 2 of 2

?

What HTML tag does JSONP exploit to bypass strict cross-domain security policies?