How to solve the JavaScript cross-domain problem

Xiaobian to share how to solve the JavaScript cross-domain problem, I hope everyone will read this article, let us discuss together!

Tongyuan Policy: Agreement, domain name, port all the same.

Non-homologous restrictions:

cookie, localStorage, IndexDB cannot be read.

DOM cannot be obtained.

AJAX requests cannot be sent.

First, JSONP

Principle: JSON data is requested to the server by dynamically adding a

element. Server Receive request returns to the specified name called callback function.

EG: Function AddScript (SRC) {var script = document.createElement (‘script’); Script.setttribute (“Type”, “Text / Javscript “); script.src = src; document.body.Appendchild (script);} WINDOW.Ont (” httpscript (“;} Function GetData Data) {console.log (data)}

Note: 1,

In the URL of the query, Callback needs to specify the name of the callback function.


The browser is run as code, the defined getData function is called immediately. 3, returned JSON parameters as jAvascript object, not a string, no JSON conversion is required.
 4, the jQuery library $ .Getjson () can also be implemented.   $. Getjson ("", Function (data) {console.log (data)}) 

Defect: is GET mode acquisition, does not support POST.
Second, Window.PostMessage

WINDOW.POSTMESSAGE is allowed to communicate across window regardless of whether homologousness is allowed. PostMessage Parameters First, Parametric 2 is the protocol + domain name + port or (* means no restrictions)

  page 1: " //Page1.html "// Pass page  Window.onLoad = function () {if (typeof window.postMessage === undefined) {Alert (" Browser does not support PostMessage! ");} else {WINDOW.Open .postMessage ({Data: "Hello World"}, "");}} 

Page 2: “” // Receive page WINDOW.ADDEVENTLISTENER (‘Message’, Function (E) {Console.log (E.DATA);}, false;

event receives Window.AddeventListener (‘Message ‘, Function () {}), the Message event object Event has three attributes:
 1, Event.Source: Window Send Messages    2, Event.origin: Message-switched URL  
3, Event.Data: Message Content
  // Reference Parent Window Send Information to the next Window.AddeventListener ('Message', ReceiveMessage); Function ReceiveMessage (Event) {Event.Source.PostMessage ('Nice to See you!', '*');}    

// Filtering is not the information sent to this window Window.addeventListener (‘Message’, ReceiveMessage); Function ReceiveMessage (Event) {if (Event.ORIGIN! == ‘http: // ‘) Return; if ( ===’ Hello World ‘) {Event. Source.postMessage (‘Hello’, Event.origin);} else {console.log (ELENT.DATA);}}

Iframe loaded into the page and the target domain in the SRC is the same domain, which is an AJAX request (parentian window). / / Prerequisite is the same source, and the different source cannot initiate a JAX request.

Different window homologs can get a Window object, but the properties and methods of the Window object cannot be obtained. // Different sources will report an error
 1, Document.domain + iframe (homologous-across domain)   Document.Domain property: The primary domain name is the same, the secondary domain name can be Implement Window object acquisition.   
Page 1: “” window.onload = function () {document.domain = “https: // segmentfault. COM / “; // Set domain window.getdata = function () {// ajax request}}
   Page 2:" HTTPS: / /SEGMENTFAULT.COM/Page2.html"
// Dynamically create iFrame optim, get data destruction. //Document.domain is set to itselfOr higher levels of parent domains, the main domain must be the same. Document.domain = “” Set Domain function test () {var win = document.getlementByid (“iframe”). ContentWindow; Win.GetData (“ JSON_DOMAIN.PHP “, function () {})}

Defect: The main domain is consistent .

2, + iframe (non-homologous)


In a window life cycle, whether or not Source, the load page of the same window property is shared, each page can be operated.

Page 1: “” = “this is data!”
     Page 2: "" 
// Dynamic Create IFRAME is the best, acquired Data is destroyed. // Get a Window.Name Function Test () {var WinName = Document.getElementById (“iframe”). ContentWindow.Name; WiNName.SRC = “”; // Finally, it is necessary to set the IFRAME’s SRC to a page address}
     Defects:  Compatibility is not good  

Segment identifier: The segment identifier refers to the URL ## behind. Just changing the clip identifier page does not refresh.

Page 1: “” function startRequest () {var = document.createElement (‘iFrame ‘); =’ none ‘; ifr.src =’ ‘; Document.Body.Appendchild (IFR);} Function checkhash () { VAR DATA = location.hash? location.hash.substring (1): ”;} setInterval (Checkhash, 2000);

page 2 : “Https://” function callback () {Try {parent.location.hash = ‘somedata’;} catch (e) {// i, chrome security mechanism unable to modify parent.location.hash, // So use an intermediate EXAMPLE Domain Agent iframe Var IFrProxy = Document.createElement (‘iframe’); = ‘none’; ifrProxy.Src = ‘https:/’; // Note that file in “” Document.body.Appendchild (IFRPROXY);}}
page 3: “TTPS: / ” // Because Parent.Parent and it belong to the same domain, you can change its local.parent.hocation.hash = self.location.hash.Substring (1);
   Disadvantages: Data exposure is in URL, and there is also a limit.   Four, WebSocket   
WebSocket: The browser sends a building to the server via JavaScriptThe BSocket connection request, after the connection is established, the client and the server can directly exchange data through the TCP connection.

Sets WebSocket request header information, the server support can be performed. ORIGIN: // Depending on whether the domain name is in the white list to determine if it can be communicated

Disadvantages: High cost.

V. Cors
 CORS is cross-domain resource sharing. The key to the CORS communication is the server. As long as the server implements a CORS interface, you can communicate across.  Disadvantages:  Server configuration, occupying the main domain bandwidth.   
After reading this article, I believe that you have a certain understanding of how to solve the JavaScript cross-domain, want to know more related knowledge, welcome to pay attention to Tumi Cloud Industry Information Channel, thank you for reading !
© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment