cool hit counter A collection of common front-end cross-domain solutions_Intefrankly

A collection of common front-end cross-domain solutions

When a browser requests a resource from a different domain, Will request unsuccessful due to homology policy, This is commonly referred to as“ Cross-domain issues”。 As a front-end developer, Resolving cross-domain issues should be a skill that is mastered。 And as technology continues to change, Various solutions have also been derived for the cross-domain problem。 We usually vary depending on the needs of the project, And taking a different approach。 This article., Will summarize in detail the knowledge points related to cross-domain issues, so that in the event of the same problem, Can there be a clear solution thinking。

Generation of cross-domain issues

Cross-domain is a class of request scenarios restricted by browser homologation policies.

homologation strategy(SOP) It's an agreement., due toNetscape company1995 Browsers introduced in 2007, It is the core and most essential security feature of the browser, If the homologation strategy is missing, The browser is vulnerable toXSS、CSFR waiting for an attack。 By homologation is meant" agreements+ domain name+ port" All three are the same., Even if two different domains point to the sameip address, Nor is it homologous。

The homologation strategy restricts the following types of behavior.

Cookies, LocalStorage and IndexDB cannot be read

DOM and JS objects are not available

AJAX requests cannot be sent

Common cross-domain scenarios

Methods for resolving cross-domains

Cross-domain via jsonp

document.domain + iframe cross-domain

location.hash + iframe + iframe cross-domain

postMessage cross-domain

Cross-domain resource sharing (CORS)

nginx proxy cross-domain

nodejs middleware proxy cross-domain

WebSocket Protocol Cross-Domain

Here's a selection of a few simple and common front-end cross-domain solutions

Cross-domain via jsonp

Principle: dynamically create script tags, and use script's src not constrained by the same source policy to get data across domains.

Advantages: good compatibility with browsers.

Disadvantages: can only be used for GET requests and requires back-end cooperation to make certain changes to the interface.

Native js implementation of jsonp

// Callback functions

function showData(data) {

for (let i in data) {

console.log(i + ':' + data[i]);



function getInfo() {

const script = document.createElement('script');

const url = 'http://xxxx/xx.php?callback=showData';

script.type = 'text/javascript';

script.setAttribute('src', url);



// Called when needed


When getInfo() is executed, http://xxxx/xx.php?callback=showData requesting is sent, and when the interface is requested normally, the server will return the data directly, e.g.; and when jsonp is used, the server will accept this callback parameter and then wrap the data to be returned with this parameter value, e.g. showData(), and the function will be executed immediately.

jQuery implements jsonp


url: 'http://xxx/xx?callback=?', // No callback name specified, omittablecallback parameters, comprisejQuery automatic generation

dataType: 'jsonp',

jsonpCallback: 'demo', // For adding your own callback functions, Without this, the callback function defaults tosuccess

success: function(data) {




Using $. Ajax method, just specify the dataType as jsonp.

document.domain + iframe cross-domain

It is mainly used to interact between pages with the same main domain and different subdomains.

Prerequisite: the two domains must belong to the same base domain! And the protocols and ports used have to be the same, otherwise you can't use document.domain for cross-domain.

Principle: Both pages achieve the same domain by forcing document.domain to be the base primary domain via js.

document.domain = '';

var user = 'index';

document.domain = '';

// Get the variables in the parent window

If document.domain is not set on both pages, the content of page b is visible in page a, but you cannot manipulate it via js. Because the two pages have the same main domain and different subdomains, before the operation, js will detect if the domains of the two pages are equal, if they are equal, it will allow its operation, if not, it will reject the operation.

We set the domain of the two pages to be the same by setting document.domain so that they can operate with each other between the two pages.

location.hash + iframe

Principle: a.html wants to communicate with b.html across domains, through the intermediate page c.html to achieve this. Three pages, using iframe's location.hash to pass values between different domains, and direct js access to communicate between the same domains.


Cross-domains with completely different domain names can be resolved.

Two-way communication is possible.


location.hash is exposed directly in the URL and generates a history in some browsers, which is not very secure and affects the user experience.

(a) The amount of data supported for delivery is not large due to URL size limitations.

A new proxy file needs to be added to enable data transfer.

As an example.


Implementation: interaction between first.html and second.html


first.html introduces second.html via an iframe.

second.html introduces cross.html via an iframe.

cross.html is in the same domain as first.html and can be accessed directly via js to communicate.

var iframe = document.getElementById('iframe');

function onCallback(hash) {

if (hash === '#red') {

document.getElementById('btn').style.color = 'red';



function changeColor() {

iframe.src = iframe.src + '#red';


var iframe = document.getElementById('iframe');

window.onhashchange = function () {

const hash = location.hash;

iframe.src = iframe.src + hash;


window.onhashchange = function () {


In first.html, we define a callback function onCallback(), which serves to change the color of the button to red and execute the changeColor() event when we click the button, passing the hash value to second.html.

in second.html, bind the onhashchange event, when the hash value changes, because second.html and first.html are not the same domain, at this time, directly execute the onCallback() event in first.html, will prompt the cross-domain operation error message, so we will pass the hash value to cross.html.

In cross.html, bind the onhashchange event, when the hash value changes, because cross.html and first.html are in the same domain, so you can execute the onCallback() event in first.html.

This enables communication between first.html and second.html. + iframe cross-domain

Principle: window object has a name property, the property has a feature that in the life of a window (window), all the pages loaded by the window are shared a, each page has read and write access to, is persistent in all the pages loaded by a window, and will not be reset due to the loading of new pages, and can support very long name values (2MB).

For example there is a pages that needs to be fetched by js in the a.html page for another page The data in the that is on a different domain.


function getData() {

var iframe = document.getElementById('iframe');

iframe.onload = function () {

//at this point the iframe and a.html are in the same domain and can access each other

var data =;



The content in //about:blank, javascript: and data:, inherits the source of the page that loaded them, and can be set to Any page under here as well.

iframe.src = 'about:blank';


b.html( = '';

a.html introduces b.html through the iframe, and executes the getData() function when the iframe is loaded. Because a.html and b.html are different domains, so a.html cannot directly get the name value in the iframe, and the role of the getData() function is to set the iframe and a.html to the same domain, so that a.html can access the data in the iframe.

The above code is just a demonstration of how can be used for cross-domain operations, the actual application we can encapsulate the process, such as the dynamic creation of iframe, in order to be safe, after getting the data, but also need to destroy the iframe, here no longer demonstrate.

postMessage cross-domain

In HTML5, a very useful method has been added to the window object: the


windowObj : The Window object that accepts the message.

message : can be an object in the latest browsers.

targetOrigin : The source of the target, * indicates arbitrary.

You can use it to send messages to other window objects, regardless of whether the window object belongs to the same source or different sources. Currently IE8+, FireFox, Chrome, Opera and other browsers have supported the window.postMessage method.

For example, there are two pages:, use window.postMessage to enable the two pages to communicate with each other.


var iframe = document.getElementById('iframe');

iframe.onload = function () {

var data = {

name: 'eric',

age: 27,

sex: 'man'


// Send cross-domain numbers to b.html



// Accept b.html return data

window.addEventListener('message', function (e) {

alert('data from b.html ---> ' +;



// Receive data from a.html

window.addEventListener('message', function (e) {

alert('data from a.html ---> ' +;

var data = JSON.parse(;

if (data) {

data.number = 16;

// Processed and sent back to a.html



When the a.html page is loaded, it transmits cross-domain data to b.html. b.html receives that data, does some processing and then returns it to a.html.

One of the message events is used to receive requests sent by postMessage. The following properties are available for function parameters.

origin : The source of the window that sent the message.

data :: Data.

source : The Window object to which the message is sent.

Cross-domain resource sharing (CORS)

CORS It's aW3C standardized, The full name is" Cross-domain resource sharing"(Cross-origin resource sharing)。

It allows the browser to cross-source server, issued XMLHttpRequest request, thus overcoming the AJAX can only be used with the source of the limitations.

CORS requires both browser and server support. Currently, all browsers support this feature, and Internet Explorer cannot go below IE10.

For a detailed explanation, please refer to Yifeng Ruan's article: Cross-Domain Resource Sharing CORS Explained (, which is mainly set up on the server side, and here is a simple example to demonstrate.

Front End Setup.

var xhr = new XMLHttpRequest(); // IE8/9 requires window. XDomainRequest compatible

// Front-end settings with or without cookies

xhr.withCredentials = true;'post', '', true);

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');


xhr.onreadystatechange = function() {

if (xhr.readyState == 4 && xhr.status == 200) {




Java backend.


* Defined in the interface parameters: HttpServletResponse response


response.setHeader("Access-Control-Allow-Origin", ""); // If there is a port, write all( agreements+ domain name+ port)

response.setHeader("Access-Control-Allow-Credentials", "true");

PHP backend.

// Set to allow access to other domains


// Set the allowed response types

header('Access-Control-Allow-Methods:POST, GET');

// Set the allowed response headers


NodeJs backend.

var http = require('http');

var server = http.createServer();

var qs = require('querystring');

server.on('request', function (req, res) {

var postData = ' ';

// Data block receiving in progress

req.addListener('data', function (chunk) {

postData += chunk;


// Data reception is complete

req.addListener('end', function () {

postData = qs.parse(postData);

// Cross-domain backend settings

res.writeHead(200, {

'Access-Control-Allow-Credentials': 'true', // The backend allows the sending ofCookie

'Access-Control-Allow-Origin': '', // Domains allowed to be accessed( agreements+ domain name+ port)

'Set-Cookie': 'l=a123456;Path=/;;HttpOnly' // HttpOnly: Script cannot be readcookie







console.log('Server is running at port 8080...');

Here we recommend to refer to a case written by Xinxu Zhang: CORS ajax cross-domain request php simple complete case one ( to aid learning.

------------ Laugh at life to penetrate the fog; laugh at life to persevere; laugh at life to resolve crises; laugh at life to illuminate the darkness.

1、Un Lei Intelligence Artificial Intelligence AI may put you out of work in the future
2、Python Fundamentals III Introduction to Classes and Objects
3、Kyushu unlikely to open blockchain in five years End of 2018 mainstream value coin price prediction
4、How to make cheat Apple version of Da Qin Huyu Fry Gold Flower cheat Apple phone
5、Byebye paper boarding passes Yinchuan airport one pass face recognition is too convenient

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送