HTML5 postMessage cross-domain exchange of data

Source: Internet
Author: User
Tags script tag

Objective

Before we briefly explained the use of the script tag (JSONP) and the IFRAME tag (window.name, Location.hash) to exchange data across domains, today we'll learn about the HTML5 API and use PostMessage to exchange data across domains. And some of the previous ways to Exchange data, the use of PostMessage can not exchange data with the server, only two windows (IFRAME) between the exchange of data , nonsense said, we directly into the actual combat.

Combat PostMessage
    • Overview

As mentioned above, PostMessage is used to exchange data between two windows (IFRAME), if we open two pages of Baidu and Google at the same time, is it said that between the two can communicate? No,no,no, this is not the case, even if Baidu and Google both pages have the will to communicate. Two windows can communicate if a window exists in the form of an iframe in another window, or if a window is opened from another window via window.open () or a hyperlink (you can also use Window.opener to get the source window) In other words, if you want to exchange data, you must be able to get a reference to the target window, otherwise there is no connection between the two windows and there is nothing you can do to communicate.

Since it is the H5 family, we also have to wait and see if it is accepted by the majority of browsers (specific details check can I use postMessage), can be seen the degree of acceptance or is quite high:

And the way PostMessage is used is fairly simple:

Otherwindow.postmessage (Message, Targetorigin, [transfer]);

Otherwindow is a reference to the receiver window, which can generally be in the following ways:

Window.frames[0].postmessage document.getelementsbytagname (' iframe ') [0]. ContentWindowwindow.opener.postMessageevent.source.postMessagewindow.open returns a reference ...

The message, as its name implies, is the data content that is sent, supporting almost all forms of data, such as strings, numbers, and JSON (see the Structured clone algorithm)

Targetorigin is the recipient's URI (protocol + host + port) or URL form, but the contents (such as xx.html) are automatically ignored, and wildcard * can be used to specify all domains, but remember not to use (for security).

Transfer can be omitted, do not understand what meaning ... We'll study it later if I need it.

The receiving window generally listens to the message event, as described in the following example.

    • Window <-> iframe

Assuming that the index page has an IFRAME (not homologous), we want to send data to the IFRAME, and the IFRAME gets the data and sends the data to the top window, indicating that "I" got the data. Look directly at the source code (think how to send and how to receive):

<!--http://localhost:81/fish/index.html-<script type= "Text/javascript" >  // The DOM node (IFRAME)  is not available until the page has finished loading function () {    // Send data document.getElementsByTagName (' iframe ') to the target source    [0]. Contentwindow.postmessage ({"Age": ten}, ' http://localhost:8080 ');  };   // Listen, there's no data sent.  function (e) {      console.log (e);  }); </script><iframe src= "http://localhost:8080/index.html" ></iframe>
<!--http://localhost:8080/index.html --<script type= "Text/javascript" >//Listen, there's no data sent.Window.addeventlistener (' message ',function(e) {//determine if the data sender is a reliable address      if(E.origin!== ' http://localhost:81 ')        return; //Print Data FormatConsole.log (e); //Postback DataE.source.postmessage (' Hello World ', E.origin); }, false);</script>

Let's see what the print looks like (the index page passes to the IFRAME data):

The red box is the three most important attribute, data is the name of the transmission, the origin is the source of the message window (URI protocol + host + port), and source can refer to the Window object that sends the message (which can be used to refer to the sending window for message callbacks).

Listening on the message receiving side can listen to the message event (code as above), of course, if you want to be compatible with the pit dad ie must use attachevent. It is not recommended to use Window.onmessage, which is not very compatible (for example, low-version ff).

    • Window <-> window

The

Finishes the data exchange with the IFRAME on the same page, and then the data exchange between the two windows. We know that using window.open () can open a new window, and if two windows are homologous, the communication of two windows will be very simple, we can call the original window method (and variable) through Window.opener.functionName in the new window. But if two windows different source, this kind of operation will become very difficult, fortunately H5 gives us the postMessage, makes Window.opener.postMessage () will not error! The demo is simple:

 <!--http:// localhost:81/fish/ Index.html-->  <script type= "Text/javascript" > //  Open a new window  var  popup = window.open (' http://localhost:8080/index.html ') Span style= "color: #000000;"  >);  // /when the popup had fully loaded, if not Blocked by a popup blocker:  setTimeout (function   () { //  The current window passes data to the target source  popup.postme  Ssage ({"Age": ten}, ' http://localhost:8080 '  1000);  </script> 
<!--http://localhost:8080/index.html-<script type= "Text/javascript" >   //  Set the Listener and print  function(e)    {console.log (e) If there is data coming in. // Console.log (E.source = = = Window.opener);  True  }); </script>

The reason to set a timer here is to send data to the target window must be complete loading of the target window, that is, in the target window to set the "listener", send the data sent to the window can be listened to, so gave a timer delay, The delay value of the timer cannot be determined because of the uncertainty of the loading time, and another feasible way is to send a message to the source page (PostMessage) after the target page has been loaded, and the source page receives the message, then sends the message to the target page with PostMessage.

Security concerns

Referring to cross-domain Exchange data, the reflex will ask, safe? For PostMessage, the answer is yes.

The PostMessage uses a "two-way security mechanism". When the sender sends the data, it confirms the source of the recipient (so it is best not to use *), and when the receiving party hears the message event, it can also use Event.origin to determine whether it is from the correct and reliable sender.

Reference
    1. Window.postmessage ()
    2. PostMessage Use of HTML5
    3. Cross-window Messaging with PostMessage
    4. HTML5 PostMessage and OnMessage API detailed application

HTML5 postMessage cross-domain exchange of data

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.