Multi-domain method _javascript techniques for JS implementation

Source: Internet
Author: User
Tags script tag what php

Speaking from the domain

domain: domain is the security boundary of the Win2K network system. We know that the most basic unit of a computer network is "domain", which is not unique to Win2K, but the Active Directory can run through one or more domains. On a stand-alone computer, the domain refers to the computer itself, a domain can be distributed across multiple physical locations, while a physical location can divide different network segments into different domains, each with its own security policy and its trust relationship with other domains. When multiple domains are connected through a trust relationship, the Active Directory can be shared by multiple trusted domain domains
domain tree: A domain tree consists of multiple domains that share the same table structure and configuration to form a contiguous namespace. The domains in the tree are connected by trust relationships, and the Active Directory contains one or more domain trees. Domains in the domain tree are connected by two-way transitive trust relationships. Because these trust relationships are two-way and transitive, the newly created domain in the domain tree or forest can immediately establish a trust relationship with each of the other domains in the domain tree or forest. These trust relationships allow a single sign-on process to authenticate users on all domains in the domain tree or forest, but this does not necessarily mean that authenticated users have the same rights and permissions in all domains in the domain tree. Because domains are security boundaries, users must be assigned the appropriate rights and permissions on a per-domain basis.
The deeper the domain hierarchy in the domain tree, the lower the level, a "." Represents a level.
such as Domain zhidao.baidu.com (Baidu know) than Baidu.com (Baidu) This domain level is low, because it has two levels of relationship, and baidu.com only one level.

What is cross-domain

By default, a XHR object can only access resources that reside in the same domain as the page that contains it. This security policy can prevent certain malicious behavior. However, implementing a reasonable Cross-domain request is also critical to developing some browser applications.
As long as the protocol, domain name, port has any one different, are treated as a different domain

For example, in the Http://www.a.com/a.js page to the following page to send an AJAX request, the following is its request results and instructions

The differences between ports and protocols can only be resolved by the background. We're going to solve the problem of different domain names.

How to cross Domain

(i) CORS (Cross-origin Resource sharing, cross source resource sharing)

1.CORS (Cross-origin Resource sharing, cross-source resource sharing) is a working draft of the consortium that defines how browsers and servers should communicate when a cross source resource must be accessed. The basic idea behind CORS is to use a custom HTTP header to communicate with the server to determine whether the request or response should be successful or fail.
2. This function is very simple, just send a response header by the server.

Browser support situation:

    • IE 8+
    • Firefox 3.5+
    • Opera 12+
    • Safari 4+
    • Chrome 3+

Suppose our page or application is already on the http://www.a.com/, and we intend to extract the data from the http://www.b.com request. In general, if we use AJAX directly, the request will fail, and the browser will return an error.
You can allow requests from http://www.a.com by simply adding one header to the cors,http://www.b.com.
The following are the settings in PHP, and the "*" sign allows any domain to submit a request to our server:

header{"Access-control-allow-origin: *"}

Cors's compatibility notation

 function Createcorsrequest (method, url) {
 var xhr = new XMLHttpRequest ();
 Non IE browser
 if ("Withcredentials" in xhr) {
 Xhr.open (method, URL, true);
 IE Browser
 } else if (typeof xdomainrequest!= "undefined") {
 vxhr = new Xdomainrequest ();
 Xhr.open (method, url);
 else {
 xhr = null;
 }
 return xhr;
 }
 var request = Createcorsrequest ("Get", "http://www.somewhere-else.com/page/");
 if (request) {
 request.onload = function () {
 //Request.responsetext processing
 };
 Request.send ();
 }

(ii) JSONP (JSON with Padding-filled JSON or parametric JSON)

In JS, although we can not directly use XMLHttpRequest request data on different fields, but on the page to introduce a different domain JS script file is possible, JSONP is to use this feature to achieve

JSONP consists of two parts: the callback function and the data. A callback function is a function that should be called on the page when the response arrives, and the data is the JSON data in the incoming callback function.

For example:

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

First, the first script note defines a function that processes the data;
Then the second script tag loads a JS file, http://example.com/data.php is the address of the data, but because it is introduced as JS, so http://example.com/data.php The return must be a JS file that can be executed;
When the last JS file is loaded, it executes the function we specified in the URL parameter and passes the JSON data we need as parameters. So that's what PHP should be like.

<?php
$callback = $_get[' callback '];//get callback function name
$data = Array (' A ', ' B ', ' C ');//The data to be returned
echo $callback. ' ('. Json_encode ($data). ') '; /Output
?>

Finally, the output result is: dosomething ([' A ', ' B ', ' C ']);
From the above you can see that JSONP is required to the server side of the page to match the corresponding.

Advantages and disadvantages of JSONP
Advantages:

It is better compatible and can be run in older browsers without the need for XMLHttpRequest or ActiveX support;
Direct access to response text, support for bidirectional communication between browser and server
Disadvantages:

JSONP is loading code execution from another domain. If other domains are not secure, it is likely that some malicious code will be entrained in the response, and there is no way to prosecute it except to completely discard the JSONP call. So when using a Web service that is not your own operation, make sure it is safe and reliable.
It only supports GET requests but not other types of HTTP requests such as post, it only supports Cross-domain HTTP requests, and does not solve the problem of how to make JavaScript calls between two pages in different domains.
(iii) Window.name

The Window object has a Name property that has a feature: in the life cycle of a window (Windows), All the pages loaded in the window are shared by a window.name, each page has read and write permission to the Window.name, Window.name is persisted in all pages that have been loaded in a window and will not be reset by the load of the new page.

Here are three pages:

A.com/app.html: Application page.
A.com/proxy.html: Agent file, is generally an HTML file without any content, need and apply the page under the same domain.
B.com/data.html: The page where the application page needs to get the data, can be called the data page.

App.html

<iframe src= "b.com/data.html" id= "iframe" ></iframe>
<script>
 var iframe = document.getElementById ("iframe");
 IFRAME.SRC = "a.com/proxy.html";//This is a page with a.com/app.html origin
 iframe.onload = function () {
 var data = Iframe.contentWindow.name; Access to Data
 }

</script>

Data.html

<script>/
 /Here is the data to be transmitted, the size generally for 2m,ie and Firefox can be large to 32M or so
 //data format can be customized, such as JSON, string
 window.name = "Data"
</script>

The first address of the IFRAME is b.com/data.html, so the window.name data can be taken;
But the IFRAME now and app.html is not homologous, app.html can not get data, so the link to the IFRAME jump to a.com/proxy.html this proxy page, now app.html and IFRAME on the same origin.

Note: The IFRAME jumps from b.com/data.html to the A.com/proxy.html page, and the value of window.name is unchanged

After the data is obtained, the IFRAME is destroyed and the memory is freed, which guarantees security (not accessed by the other domain frame JS).

<script type= "Text/javascript" >
 iframe.contentWindow.document.write (');
 Iframe.contentWindow.close ();
 Document.body.removeChild (IFRAME);
</script>

(iv) Document.domain + IFRAME

Examples of the same primary domain and different subdomains can be resolved by setting up a Document.domain method.
The specific approach is to set document.domain = ' a.com ' in the two files in http://www.a.com/a.html and http://script.a.com/b.html, respectively. Then through the a.html file to create an IFRAME, to control the contentdocument of the IFRAME, so that two JS files can be "interactive".
Http://www.a.com/a.html page

<iframe src= "http://script.a.com/b.html" frameborder= "0" ></iframe>
<script>
 Document.domain = ' a.com ';
</script>

Http://script.a.com/b.html page

<script>
 document.domain = ' a.com ';
</script>

Such two pages can be accessed through JS each of the various properties and objects.

The document.domain settings are limited , and we can only set the document.domain to a parent domain of its own or higher, and the primary domain must be the same. For example, the document.domain of a document in a.b.example.com can be set to either a.b.example.com, b.example.com, or example.com, but cannot be set to C.a.b.example.com, because this is a subdomain of the current domain and cannot be set to baidu.com because the primary domain is already different.

(v) Window.postmessage of HTML5

The Window.postmessage (Message,targetorigin) method is HTML5 new introduced feature that can be used to send messages to other window objects, regardless of whether the window object belongs to a homologous or different source, currently ie8+, Firefox, Chrome, opera and other browsers have supported the window.postmessage approach.
Window.postmessage allows data messages to be sent across domains between two windows/frames. Essentially, Window.postmessage is a cross-domain ajax with no server shim.

Usage:
otherwindow.postmessage (message, targetorigin);

    • Otherwindow: A reference to the window that receives the information page. Can be the Contentwindow property of the IFrame in the page, the return value of the Window.+open, and the value that is fetched from the Window.frames by name or subscript.
    • Message: The data to be sent, string type.
    • Targetorigin: Used to limit Otherwindow, "*" means no restrictions

Data sending end
code in a.com/index.html:

<iframe id= "IFR" src= "b.com/index.html" ></iframe>
<script type= "Text/javascript" >
Window.onload = function () {
 var IFR = document.getElementById (' IFR ');
 var targetorigin = ' http://b.com '; Sets the domain of the receiving end, * is not limited to
   
 ifr.contentWindow.postMessage (' I was there! ', targetorigin);
</script>

Data receiving end
code in b.com/index.html:

<script type= "Text/javascript" >
 window.addeventlistener (' message ', function (event) {
 / To determine the message source address
 if (event.origin = = ' http://a.com ') by Origin property {
 alert (event.data);//Eject "I was there!"
 alert (Event.source); References to a.com, index.html window objects
   //But because of the homology policy, the Window object
 }
 , False is not accessible here Event.source;
</script>

The above is JS to achieve a wide range of methods, I hope to help you learn.

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.