What is exactly cross domain call?

Learn what is exactly cross domain call? with practical examples, diagrams, and best practices. Covers cross-domain development techniques with visual explanations.

Understanding Cross-Domain Calls: The Basics of Web Communication

Hero image for What is exactly cross domain call?

Explore what cross-domain calls are, why they exist, and the security implications and mechanisms involved in modern web development.

In the world of web development, you'll frequently encounter the term "cross-domain call." This concept is fundamental to how web applications interact with resources and services across the internet. At its core, a cross-domain call refers to a request made from a web page in one domain to a resource (like an API endpoint, an image, or a script) located on a different domain. While seemingly straightforward, this interaction is heavily governed by security policies, primarily the Same-Origin Policy, which aims to protect users from malicious websites.

What Defines a 'Domain' in Web Context?

Before diving into cross-domain calls, it's crucial to understand what constitutes a "domain" in the context of web security. The Same-Origin Policy defines an origin by combining three components: the scheme (protocol), the host (domain name), and the port number. If any of these three components differ between two URLs, they are considered to be from different origins, and thus, a request between them is a cross-domain call.

flowchart TD
    A[Origin 1: https://www.example.com:443] --> B{Scheme Match? (https == https)}
    B -->|Yes| C{Host Match? (www.example.com == www.example.com)}
    C -->|Yes| D{Port Match? (443 == 443)}
    D -->|Yes| E[Same Origin]
    D -->|No| F[Cross-Domain (Port Mismatch)]
    C -->|No| G[Cross-Domain (Host Mismatch)]
    B -->|No| H[Cross-Domain (Scheme Mismatch)]

Determining Same-Origin Policy Compliance

For example:

  • https://www.example.com/page1.html and https://www.example.com/page2.html are same-origin.
  • https://www.example.com and http://www.example.com are different origins (scheme mismatch).
  • https://www.example.com and https://api.example.com are different origins (host mismatch).
  • https://www.example.com:8080 and https://www.example.com:443 are different origins (port mismatch).

The Same-Origin Policy and Its Purpose

The Same-Origin Policy (SOP) is a critical security mechanism implemented by web browsers. It restricts how a document or script loaded from one origin can interact with a resource from another origin. The primary purpose of SOP is to prevent malicious scripts on one page from accessing sensitive data on another page. Without SOP, a malicious website could, for instance, load your banking website in an iframe and then use JavaScript to read your account balance or even initiate transactions.

Common Techniques for Cross-Domain Communication

While the Same-Origin Policy is a security cornerstone, modern web applications often need to communicate across different origins. Several techniques have been developed to safely enable cross-domain calls, each with its own use cases and considerations.

1. Cross-Origin Resource Sharing (CORS)

CORS is the most widely adopted and recommended standard for enabling cross-domain requests. It's a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin permission to access selected resources from a different origin. The server hosting the resource explicitly grants permission to the requesting origin.

GET /data HTTP/1.1
Host: api.example.com
Origin: https://www.frontend.com

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://www.frontend.com
Content-Type: application/json
{
  "message": "Data from API"
}

Example of a simple CORS request and response headers

2. JSONP (JSON with Padding)

JSONP is an older technique that bypasses the Same-Origin Policy by leveraging the fact that browsers allow <script> tags to load resources from any domain. A JSONP request involves dynamically creating a <script> tag whose src attribute points to the cross-domain URL. The server then wraps the JSON data in a JavaScript function call, which is executed when the script loads.

function handleData(data) {
  console.log(data);
}

// Dynamically create a script tag
const script = document.createElement('script');
script.src = 'https://api.example.com/data?callback=handleData';
document.head.appendChild(script);

// Server response would look like:
// handleData({"message": "Data from API"});

Client-side JSONP request and expected server response format

3. Proxy Servers

Another common approach is to use a proxy server. In this setup, the client-side application makes a request to its own origin (the proxy server), which then forwards the request to the target cross-domain server. The proxy server receives the response and sends it back to the client. Since the client-side request is always to the same origin, the Same-Origin Policy is not violated.

sequenceDiagram
    participant Client
    participant ProxyServer as Proxy Server (Same Origin)
    participant RemoteAPI as Remote API (Cross-Domain)

    Client->>ProxyServer: Request data (e.g., /api/data)
    ProxyServer->>RemoteAPI: Forward request (e.g., GET https://remote.com/data)
    RemoteAPI-->>ProxyServer: Send data response
    ProxyServer-->>Client: Send data response

Cross-domain communication via a proxy server

4. postMessage API

The window.postMessage() method provides a secure way for different origins to communicate with each other. It's particularly useful for communication between a parent window and an iframe, or between different windows/tabs, without violating the Same-Origin Policy. It allows messages to be sent and received safely by specifying the target origin.

// In parent window (e.g., https://parent.com)
const iframe = document.getElementById('myIframe');
iframe.contentWindow.postMessage('Hello from parent!', 'https://child.com');

// In iframe (e.g., https://child.com)
window.addEventListener('message', (event) => {
  if (event.origin === 'https://parent.com') {
    console.log('Received message from parent:', event.data);
    event.source.postMessage('Hello from child!', event.origin);
  }
});

Using postMessage for secure cross-origin communication