DEV Community

Cover image for What is JSON with padding?
sametcodes
sametcodes

Posted on

What is JSON with padding?

JSONP (JSON with padding) is a tricky way to send cross-site GET requests by getting around the browser’s same-origin policy. The modern browsers follow the CORS rules when sending XHR (XMLHttpRequest) requests, but JSONP bypasses it due to the way how it sends requests.

JSONP isn’t an XHR request; it’s a script load on the page but returns a function call. This is what JSONP data looks like:

callback({
    data: {
        id: 1
    }
})
Enter fullscreen mode Exit fullscreen mode

But, what does it do exactly?

Let’s assume your web page has functions from the app.js file that loads on the page with script tags. As the page opens, the script tag will send a request for the app.js and loads it, the definition of functions will be processed onto the page, and the functions will be ready to call. This is how JavaScript files are processed.

Taken from https://stackoverflow.com/a/43835381/8574166

But, if you put an endpoint URL into the script tag with a callback parameter, the server would return only a JSONP object ready-to-call on the client if the returning function is defined on the client right after the page resolves the script tag.

Taken from https://stackoverflow.com/a/43835381/8574166

Dynamic JSONP requests

Instead of sending the requests when the page initiates, requests can be sent dynamically by injecting a script element into the DOM within a function.

function requestServerCall(url) {
  var head = document.head;
  var script = document.createElement("script");

  script.setAttribute("src", url);
  head.appendChild(script);
  head.removeChild(script);
}

function myCallback(data){
    // process your data here
}

requestServerCall("URL?callback=myCallback")
Enter fullscreen mode Exit fullscreen mode

Is it safe?

Well, no. It’s just a basic hack to make cross-domain requests, and sites that use JSONP services are prone to CSRF; well, that’s why XHR request methods have CORS policies: to keep safe client users.

An attack that prepared for potential XSS vulnerabilities, such as stealing user cookies, can also be demonstrated for JSONP. The provider of JSONP data must be trustable and ensure that it doesn’t return any malicious JavaScript code and try to run a different callback than given.

Conclusion

JSONP is an old-fashioned and hacky way, but not safe, to send GET requests to the client. XHR requests, such as ajax and fetch, are restricted to sending cross-site requests, but it is still possible to send with JSONP.

Plus, it is not that useful to use it in JavaScript applications due to no callback functions are provided to handle potential errors, even though some libraries like jQuery and Angular implemented a native way to send JSONP requests.

So, there is no need to use it.

This blog post was published on here.

Top comments (0)