Mastering Cross-Origin Techniques: JSONP, img Ping, window.name, postMessage & CORS

Explore multiple cross-origin communication methods—including same-origin rules, JSONP, img ping, window.name, postMessage, and CORS—by understanding their principles, code examples, and server requirements, enabling developers to safely exchange data across different domains in web applications.

JavaScript
JavaScript
JavaScript
Mastering Cross-Origin Techniques: JSONP, img Ping, window.name, postMessage & CORS

Definition of same origin: two pages share the same protocol, port (if specified), and host.

Examples of same-origin checks:

http://store.company.com/dir2/other.html – Success (same origin)

http://store.company.com/dir/inner/another.html – Success

https://store.company.com/secure.html – Failure (different protocol)

http://store.company.com:81/dir/etc.html – Failure (different port)

http://news.company.com/dir/other.html – Failure (different host)

1. JSONP

The script tag bypasses the same-origin policy, allowing any external JavaScript file. JSONP works by defining a callback function on the client; the server returns JavaScript that calls this function with the data.

function jsonp_cb(data){
    console.log(data);
}
function ajax(){
    var url = "http://xx.com/test.php?jsonp_callback=jsonp_cb";
    var script = document.createElement('script');
    // send request
    script.src = url;
    document.head.appendChild(script);
}
ajax();

The server receives the callback name jsonp_cb and responds with a script that invokes it, e.g.:

jsonp_cb({"name":"story"});

2. img Ping

The img tag also has no cross-origin restriction, but it can only send GET requests and cannot read the response body. It can be used for simple one-way cross-domain communication such as tracking clicks.

var img = new Image();
img.onload = function(){
    console.log('done');
    img.onload = null;
    img = null;
};
img.src = "http://xx/xx.gif";

3. window.name

The window.name property persists across page navigations within the same protocol and can store up to about 2 MB of string data. It can be used for cross-origin data transfer via an iframe.

window.name = 'string'; // set name
console.log(window.name);
location = 'http://font.com/'; // navigate
// later in console: window.name still "string"

Example of using window.name with an iframe:

var url = "http://font.com/lab/windowName";
var iframe = document.createElement('iframe');
iframe.onload = function(){
    var data = iframe.contentWindow.name;
    console.log(data);
};
iframe.src = url;
document.body.appendChild(iframe);

Server can embed data in a script that sets window.name with JSON, e.g.:

echo '<script>window.name = "{\"name\":\"story\"}"</script>';

4. postMessage

The postMessage API enables scripts from different origins to communicate safely. The sender calls targetWindow.postMessage(message, targetOrigin), and the receiver listens for the message event.

otherWindow.postMessage(message, targetOrigin);
otherWindow

– reference to the target window (e.g., iframe.contentWindow or a window opened via window.open) message – data to transmit targetOrigin – allowed origin of the receiver

var iframe = document.createElement('iframe');
iframe.onload = function(){
    var popup = iframe.contentWindow;
    popup.postMessage("hello", "http://127.0.0.1:5000");
};
iframe.src = 'http://127.0.0.1:5000/lab/postMessage';
document.body.appendChild(iframe);

window.addEventListener("message", function(event){
    if (event.origin !== "http://127.0.0.1:5000") return;
    console.log(event.data);
    // reply
    event.source.postMessage("world", event.origin);
}, false);

5. CORS

Cross-Origin Resource Sharing (CORS) is a mechanism that allows browsers to make cross-domain AJAX requests when the server includes appropriate response headers.

Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: http://funteas.com/

When a script makes a request to another domain, browsers automatically add an Origin header containing the current host. To include cookies, set xhr.withCredentials = true on the client and the server must send Access-Control-Allow-Credentials: true.

var xhr = new XMLHttpRequest();
var url = 'http://bar.other/resources/public-data/';
xhr.open('GET', url, true);
xhr.send();

xhr.withCredentials = true;

For more details, see the MDN documentation on CORS.

Other cross-origin methods such as document.domain or Flash are omitted here.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CORSCross-OriginJSONPpostMessagesame-originwindow.name
JavaScript
Written by

JavaScript

Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.