Cross-Origin Issues and Solutions in Web Development
The article explains cross‑origin restrictions in web development, distinguishes broad and narrow cross‑origin, outlines common scenarios, and compares solutions such as JSONP, CORS, Flash, server proxies, and front‑end techniques like document.domain, hash, window.name, and postMessage, highlighting each method’s pros and cons.
In daily development, developers often encounter AJAX cross‑origin requests or front‑end cross‑origin communication scenarios. Both front‑end and back‑end engineers need to understand how to solve cross‑origin problems. This article summarizes common cross‑origin scenarios, solutions, and their pros and cons.
1. What is cross‑origin
When a page or script under a.qq.com tries to request a resource under b.qq.com , it is a typical cross‑origin request. Cross‑origin can be divided into two definitions: broad cross‑origin and narrow cross‑origin.
(1) Broad cross‑origin
Broad cross‑origin usually includes three behaviors:
Resource redirection: links, redirects.
Resource embedding: <link> , <script> , <img> , <frame> , CSS background:url() , @font-face() , etc.
Script requests: browser storage reads, DOM/JS object cross‑origin operations, AJAX requests, etc.
Resource redirection and embedding can normally fetch cross‑origin resources, while script requests usually encounter cross‑origin issues.
(2) Same‑origin policy (SOP)
SOP, introduced by Netscape in 1995, is the core security mechanism of browsers. It requires that the protocol, domain, and port be identical for two pages to be considered same‑origin.
(3) Narrow cross‑origin
Narrow cross‑origin refers to the specific request scenarios restricted by SOP, typically including:
Cookies, localStorage , IndexedDB cannot be accessed.
DOM and JS objects cannot be accessed or manipulated.
AJAX requests cannot be sent.
2. Common cross‑origin scenarios
Various situations where cross‑origin occurs in web applications.
3. Cross‑origin solutions
(1) AJAX cross‑origin solutions
JSONP : Uses a <script> tag to request data. The server wraps the response in a callback function specified by the client.
Code example:
var script = document.createElement('script');
script.type = 'text/javascript';
// Pass callback to backend, backend returns data wrapped in the callback
script.src = 'http://a.qq.com/index.php?callback=handleCallback';
document.head.appendChild(script);
function handleCallback(res) {
alert(JSON.stringify(res));
}Advantages: strong compatibility, works in IE10 and below.
Disadvantages: only GET requests, no error handling, possible XSS via callback injection, cannot set response headers.
CORS (Cross‑Origin Resource Sharing) : W3C standard that allows browsers to send cross‑origin requests when the server includes appropriate Access-Control-Allow-Origin headers.
Simple CORS request flow:
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', 'http://a.qq.com/index.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=saramliu');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};Advantages: supports all HTTP methods, can send cookies, full header control.
Disadvantages: requires browser and server support; IE8/9 need XDomainRequest , older browsers do not support.
Flash cross‑origin (for IE7 and below) : Uses a Flash object to perform cross‑origin requests after the browser checks crossdomain.xml .
Typical crossdomain.xml example:
<cross-domain-policy>
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*.qq.com"/>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>Advantages: works without modifying backend, compatible with very old browsers.
Disadvantages: depends on Flash plugin support, security risks.
Server proxy : Backend forwards the request to the target server and returns the data to the front‑end, eliminating cross‑origin at the client side.
Advantages: works without Flash, can handle any request type.
Disadvantages: requires backend changes.
(2) Front‑end cross‑origin communication solutions
document.domain + iframe : Works when the main domain is the same but sub‑domains differ. Both pages set document.domain to the shared parent domain, then communicate via the iframe.
Advantages: simple logic, no extra middle page.
Disadvantages: only works for same main domain.
location.hash + iframe : Uses URL hash changes to pass data between pages with different main domains, requiring an intermediate same‑origin page.
Advantages: works for different main domains, hash change does not reload page.
Disadvantages: requires extra same‑origin intermediate page, data length limited, security concerns.
window.name + iframe : The window.name property persists across navigation and can hold up to 2 MB of data.
Advantages: supports large data, works across different main domains.
Disadvantages: needs an extra same‑origin page.
postMessage : HTML5 API for safe cross‑origin messaging between windows, iframes, and workers.
Advantages: works for many communication scenarios, supports any data type (except in older IE).
Disadvantages: not supported in IE8 and below; IE9 only supports string messages.
4. Summary
The article introduced the concept of cross‑origin restrictions, listed typical scenarios, and compared several solutions (JSONP, CORS, Flash, server proxy, document.domain, hash, window.name, postMessage) with their advantages and drawbacks. It serves as a reference for developers dealing with web cross‑origin issues.
Tencent Cloud Developer
Official Tencent Cloud community account that brings together developers, shares practical tech insights, and fosters an influential tech exchange community.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.