JSON cross-Domain solution collection

Source: Internet
Author: User

One of the most recent interview questions is the cross-domain problem of JavaScript. Here is a summary of some of the cross-domain approaches. Because of the browser's homologous policy, different domain names, different ports, different protocols will form a cross-domain, but in the actual business, many scenarios need to pass information across domains, which leads to a variety of cross-domain methods.

1. A label with SRC
    • Principle: All HTML tags that have SRC attributes can be cross-domain

In the browser, the tags for <script>, , <iframe>, and <link> can load cross-domain (non-homologous) resources and load in a way that is equivalent to a normal GET request, The only difference is that, for security reasons, the browser does not allow read and write operations to the loaded resources in this way, but only the capabilities that the tag itself should have (such as script execution, style application, and so on).

2. Jsonp Cross-domain
    • Principle: <script> is a function that can be cross-domain, and can directly callback the current script in a cross-domain script

The script tag is an exotic JavaScript that can be loaded and executed by pre-programmed callback functions to interact with the parent page. It has a name called Jsonp cross-domain, and JSONP is a JSON with padding merchants. It's an unofficial protocol, obviously loading script, why is it related to JSON? This is the callback function, the use of it has a typical way, is through the JSON to pass the parameter, the JSON data is filled into the callback function, this is the meaning of Jsonp json+padding. JSONP only supports GET requests.

Front-End Code:

<script type= "Text/javascript" > Function dosomething (jsondata) {//processing obtained JSON data}</script><script src= " Http://haorooms.com/data.php?callback=dosomething "></script>

Background code:

<?php$callback = $_get[' callback '];//gets the callback function name $data = Array (' A ', ' B ', ' C '),//The data to be returned echo $callback. ' ('. Json_encode ($data). ') '; /Output?>
3. Cross-domain resource sharing (CORS)
    • Rationale: After server settings Access-control-allow-origin HTTP response headers, the browser will allow cross-domain requests

Cors is a cross-domain resource sharing (Resource Share) HTML5 standard that supports all HTTP requests such as GET, post, and so on. Cors requires the server-side setting of the Access-control-allow-origin header, otherwise the browser will intercept the returned information because of security policy.

Access-control-allow-origin: *              # allows all domain names to be accessed, or access-control-allow-origin:http://a.com   # only allows access to all domain names

Cors is also divided into simple cross-domain and non-simple cross-domain requests, the detailed description of cors please see Nanyi cross-domain resource sharing CORS detailed, which explains in very detail.

4. Document.domain
    • Principle: The same primary domain name under different sub-domain pages, you can set document.domain let them the same domain

We just need to set document.domain on two pages across the domain. The method of modifying Document.domain only applies to the interaction between frames of different subdomains and is loaded into the IFRAME page.

For example: 1. Set Document.domain on page http://a.example.com/a.html

<iframe id = "iframe" src= "http://b.example.com/b.html" onload = "test ()" ></iframe><script type= "text/ JavaScript "> document.domain = ' example.com ';//set to primary domain function test () {alert (" document.getElementById ('. IFrame '). Contentwindow);//contentwindow can get the window object of the Subwindow}</script>

2. Set the document.domain in the page/HTTP b.example.com/b.html

<script type= "Text/javascript" > document.domain = ' example.com ';// In the iframe loading this page also set Document.domain to make it the same as the document.domain on the main page </script>
5. Window.name
    • Principle: The Window object has a Name property, which has a feature: that is, within the life cycle of a window All the pages loaded in the window are shared by a window.name, each page has permission to read and write to Window.name, and Window.name is persisted on all pages loaded in a window.

There are three pages:

    • sever.com/a.html Data storage Page

    • Agent.com/b.html Data Acquisition Page

    • agent.com/c.html empty page, do agent use

A.html, set Window.name as the value to pass

<script> window.name = ' I was there! '; Alert (window.name);</script>

B.html, when the IFRAME is loaded, the src of the iframe points to the c.html of the same domain, so that you can take the iframe.contentWindow.name to get the value to pass.

<body>  <script type= "Text/javascript" > iframe = document.createelement (' iframe '); Iframe.style.display = ' None '; var state = 0; Iframe.onload = function () {if (state = = = 1) {var data = Json.parse (iframe.contentWindow.name); alert (data); Iframe.conte NtWindow.document.write ("); Iframe.contentWindow.close (); Document.body.removeChild (IFRAME); } else if (state = = = 0) {state = 1; iframe.contentWindow.location = ' http://agent.com/c.html ';}}; IFRAME.SRC = ' http://sever.com/a.html '; Document.body.appendChild (IFRAME); </script></body>

Successful acquisition of cross-domain data results in the following:

6. Window.postmesage
    • Principle: HTML5 New PostMessage method, through PostMessage to pass information, the other side can listen to the message event to listen to information. Can span primary domain and bidirectional cross-domain.

There are two pages:

    1. Agent.com/index.html

    2. Server.com/remote.html

Local code index.html

<body>      <iframe id= "proxy" src= "http://server.com/remote.html" onload = "postmsg ()" Style= "Display:none" ></iframe>      <script type= "Text/javascript" >  var obj = {  msg: ' Hello World '  }  function postmsg () {  var iframe = document.getElementById (' proxy ');  var win = Iframe.contentwindow;  Win.postmessage (obj, ' http://server.com ');  }  </script>  </body>

How to use PostMessage: otherwindow.postmessage (message, targetorigin);

    • Otherwindow: Refers to the target window, that is, to which window to send messages, is a member of the Window.frames property or window created by the Window.Open method

    • Msg: is the message to be sent, type String, Object (IE8, 9 not supported)

    • Targetorigin: is limited to the message receiving range, do not limit the use of ' * '

Server.com on the remote.html, listen for the message event, and check to see if the source is the domain to be communicated.

7. Location.hash

Principle:

    • This method is more round, but it can solve the problem of footstep replacement in the case of complete cross-domain. The principle is to use Location.hash to transmit values. Www.a.com under the a.html want to and www.b.com under the b.html communication (in a.html dynamically create a b.html iframe to send the request)

    • But because of the "same-origin policy" restrictions they could not communicate (B.html cannot return data), so find a middleman: Www.a.com under the c.html (note is www.a.com).

    • B.html the data to C.html (an iframe created in b.html), and because c.html and a.html are homologous, the returned data can be passed back to c.html via a.html to achieve cross-domain effects.

The a.html code is as follows:

<script>function startrequest () {  var IFR = document.createelement (' iframe ');  Ifr.style.display = ' None ';  IFR.SRC = ' http://www.b.com/b.html#sayHi '; Passed Location.hash  document.body.appendChild (IFR);} function CheckHash () {  try {  var data = Location.hash ? Location.hash.substring (1): ";  if (console.log) {  Console.log (' Now the data is ' +data);  }  catch (e) {};} setinterval (CheckHash, +); wind Ow.onload = startrequest;</script>

The b.html code is as follows:

<script>function CheckHash () {var data = ';//simulate a simple parameter handling operation switch (location.hash) {case ' #sayHello ': data = ' Hellow Orld '; break; Case ' #sayHi ': data = ' Hiworld '; Default:break; } Data && CallBack (' # ' +data);} function CallBack (hash) {//IE, chrome security mechanism can not modify parent.location.hash, so to take advantage of an intermediary www.a.com domain proxy iframe var proxy = Document.createelement (' iframe '); Proxy.style.display = ' None '; PROXY.SRC = ' http://localhost:8088/proxy.html ' +hash; Note that the file is in the "www.a.com" field under Document.body.appendChild (proxy);} Window.onload = checkhash;</script>

Since two pages are not in the same domain, IE, chrome does not allow to modify the value of Parent.location.hash, so to rely on the a.com domain name of a proxy iframe, there is a a.com under the proxy file c.html. Firefox can be modified.

The c.html code is as follows:

<script>parent.parent.location.hash = self.location.hash.substring (1); </script>

Direct access a.html,a.html sends the message "Sayhi" to b.html, b.html returns "Hiworld" through the message and changes the value of c.html by Location.hash

8. Flash URLLoader

Flash has its own set of security policies that can be used by the server to declare which domain SWF files can be accessed by the Crossdomain.xml file, and SWF can also use the API to determine which domain SWF it can load. When accessing resources across domains, such as data from a domain baidu.com request domain google.com, we can use Flash to send HTTP requests. First, modify the crossdomain.xml on the domain google.com (typically stored in the root directory, if you do not need to create it manually), and add baidu.com to the whitelist. Second, send HTTP requests via Flash Urlloader, and finally pass the response results to JavaScript via the Flash API. Flash Urlloader is a common cross-domain solution, but if you need support for iOS, this is not a good solution.

Summary

In general, the common cross-domain approach is as described above. In different business scenarios, each has a suitable cross-domain approach. Cross-domain solves some of the challenges of resource sharing and information interaction, but some cross-domain approaches can pose security issues, such as JSONP that can lead to puddle attacks, and tags that can be used for XSS or CSRF attacks. Therefore, in the application of cross-domain scenarios, you need to pay extra attention to security issues.

Text of the public number

JSON cross-Domain solution collection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.