A common iframe cross-origin Communication Method

Source: Internet
Author: User

Same-origin policy Introduction
If the protocol, port (if specified), and host name of the two pages are the same, the two pages have the same source. The same-origin policy prevents you from retrieving or setting attributes of documents loaded from one source. This policy can be traced back to Netscape Navigator 2.0.

However, in many cases, pages in two different domains need to communicate with each other, which leads to the issue of cross-origin communication. There are many articles on cross-origin communication, you can refer to 10 methods to achieve cross-origin Resource Sharing. Here we will share with you how two-way cross-origin communication is implemented in our project.

Solution
For two-way cross-origin communication, there are not many options. Considering various factors, we choose the combination of FIM + window. postMessage to solve the cross-origin communication problem. Because the two methods have their own advantages and disadvantages, window. postMessage is very simple to use, but because it is a relatively new method, IE6 and IE7 are not supported by older browsers. The FIM method supports all browsers, but it is cumbersome and easy to generate browsing records. Therefore, if the browser supports window. postMessage, window. postMessage is used. Otherwise, FIM technology is used.

Window. postMessage Solution
Window. postMessage is a new method defined in html5. this method can easily communicate across windows. Because it is a new method, it cannot be used in both old and old browsers. For example, IE6 and IE7, IE8 already support this method.

Window. postMessage is easy to use. There are only two parameters. The first parameter is the message to be transmitted, and the second parameter is the message receiving domain, which can be expressed by "X. The code for sending a message is as follows:

Var o = document. getElementsByTagName ('iframe') [0];
O. contentWindow. postMessage ('Hello world', 'HTTP: // B .example.org /');
The code for receiving a message page is as follows:

Window. addEventListener ('message', receiver, false );
Function Cycler (e ){
If (e. origin = 'HTTP: // example.com '){
If (e. data = 'Hello World '){
E. source. postMessage ('hello', e. origin );
} Else {
Alert (e. data );
}
}
}
Note that the event binding method is only applicable to non-ie browsers. for IE browsers, you need to use attachEvent to bind events. In the above code, you can determine whether to determine the source of the message. Here, we consider security to prevent insecure messages.

FIM (Fragment Identitier Messaging)
FIM (Fragment Identitier Messaging) is based on the principle that iframe can be URL read and written based on the parent window, iframe can also write the URL of the parent window (note, in cross-origin, iframe cannot read the URL of the parent window, but can modify the URL of the parent window). A part of the URL is called frag, which is the # and its subsequent characters, it is generally used for browser anchor locating. The Server does not care about this part. It should be said that the HTTP request process does not carry frag, so this part of modification does not produce HTTP requests, that is, the page will not be refreshed, however, browser history is generated. The FIM principle is to change the URL's frag for bidirectional communication. Each window sends messages by changing the location of other windows, and listens for changes in its own URL to receive messages. This communication method may cause unnecessary browser history records. In addition, some browsers do not support the onhashchange event. You need to poll the changes to the URL. Finally, the URL has a length limit in the browser, this restricts the amount of data transferred each time.

The Code is as follows:
Var o = document. getElementById ('iframe ');
O. href = 'HTTP: // www.weakweb.com # name = boris ';
In this way, the value is passed to the iframe. Next we need to consider how the iframe monitors when messages are sent. There are two methods: 1. Use setInterval () Round Robin in iframe to determine whether the current iframe URL has changed; 2, change the iframe size in the parent window to trigger the iframe window. the disadvantage of the onresize event is to change the size of the iframe window. When iframe finds that a message is sent, it can be read through locaiton. hash.

Iframe sends messages to the parent window
Parent. location. href = 'HTTP: // www.company.com # height = 100 ';
As mentioned above, iframe can write the URL of the parent window but cannot be read during cross-origin, so here we pass the message to the parent window through frag. Similarly, the parent window also needs to monitor when messages are sent in. Here, only polling is used.

FIM Improvement
When the parent window uses the modification of the iframe window size to tell iframe that there is a message transmission mode, this method has a very obvious drawback, that is, the change of the iframe window size will seriously affect the user experience. Therefore, the proxy mechanism is used here for processing.

We have created an additional proxy iframe called proxyIframe. proxyIframe is in the same domain as the previous contentIframe, and proxyIframe is invisible. In this way, we first pass the message to proxyIframe, then, it is sent to contentIframe by proxyIframe. Because these two iframe values are in the same domain, they can be easily transmitted. The advantage of this is that we only modify the size of proxyIframe without modifying the size of contentIframe. This will not affect the user experience, but is a little more complicated than before.

The URL Length of the browser is limited, especially IE, so we can solve this problem through multipart transmission.

Sample Code
I wrote a test code, which contains three pages, one parent page and two iframe pages. Click to download

A simple method to test and run the above sample code locally. In the C: \ Windows \ System32 \ drivers \ etc \ hosts file, add two domain names to point to 127.0.0.1, in this way, you can test cross-origin. My hosts file is as follows:

127.0.0.1 a.com
127.0.0.1 B .com
 

Related Article

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.