Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ HTML5 postMessage cross-domain data exchange     - Multi-core CPU, multi-threading and parallel computation (Linux)

- Getting Started with Linux system to learn: how to install the kernel headers on Linux (Linux)

- Linux foreground to background process switch (Linux)

- Linux System Getting Started Learning: Debian download, installation and graphical interface (Linux)

- Compare Several MySQL environmental issues (Database)

- MySQL root password reset under CentOS (Database)

- CentOS yum source configuration (Linux)

- Kafka cluster deployment (Server)

- What happens after the MySQL disk space is full (Database)

- SA weak password security system of the security risks posed (Linux)

- Precautions against hackers Linux environment (Linux)

- Linux environment password security settings (Linux)

- Replace element and non-replaced elements of learning (Programming)

- Ubuntu install code editor Sublime Text 3 (Linux)

- Automatic and Manual Proxy Settings Switch GNOME Shell Extension Proxy Switcher Recommend (Linux)

- OpenSSL: implementation creates a private CA, certificate signing request Explanation (Server)

- Smooth upgrade to OpenSSH 6.1 Procedure (Linux)

- BCP importing and exporting large amounts of data Practice (Database)

- Java class HashSet (Programming)

- PostgreSQL Stream Configuration (Database)

 
         
  HTML5 postMessage cross-domain data exchange
     
  Add Date : 2017-04-13      
         
       
         
  Foreword

Before simply explained to use script tag (jsonp) and iframe tag (window.name, location.hash) to cross-border data exchange, today we learn about HTML5's api, postMessage use to exchange data across domains. And in front of some of the ways to exchange data in different ways that can not use postMessage and server exchange data, only the exchange of data between two windows (iframe), ado, we go directly to actual combat.

Combat postMessage

overview
Above said, postMessage is used to exchange data between the two windows (iframe) if we also open the Baidu and Google two pages, is not to say that you can communicate between the two? No, no, no, that is not true, even if Baidu and Google two pages nor the will to communicate. Two windows can communicate premise is that a window in iframe form in another window, or a window or a hyperlink that opens (can also be used window.opener get from another window by window.open () source window); in other words, you want to exchange data, you must be able to obtain the target window (target window) reference, or no contact between the two windows, to communicate can not do anything.

Since it is the H5 family, we have to wait and see that it is under (can specifics check I use postMessage) acceptance of the majority of the browser, you can see the acceptance is still quite high:

The postMessage of use is quite simple:

otherWindow.postMessage (message, targetOrigin, [transfer]);
otherWindow Is the recipient window references may generally be in the following ways:

window.frames [0] .postMessage
document.getElementsByTagName ( 'iframe') [0] .contentWindow
window.opener.postMessage
event.source.postMessage
window.open returned reference
...
The contents of the data message is sent as the name suggests, supports strings, numbers, json, almost all forms of data (see The structured clone algorithm)

targetOrigin is the recipient URI (protocol, host, port), can also be a url form, but after the content (shaped like xx.html) are automatically ignored; * wildcard can specify all domains, but remember not to use (for security ).

transfer can be omitted, I did not understand what is the meaning of ... the future when the need arises again research

The recipient window usually listens message events, see the following examples.

window < -> iframe
Suppose there is a iframe index page (different sources), we give the iframe to send data, and the data obtained after the iframe also send data to the top window, he said, "I" to get the data. Looking directly at the source code (how to think about how to send and receive):

< - Http:! // Localhost: 81 / fish / index.html ->
< Script type = "text / javascript">
  // After loading the page in order to get the dom node (iframe)
  window.onload = function () {
    // Send data to the target source
    document.getElementsByTagName ( 'iframe') [0] .contentWindow.postMessage ({ "age": 10}, 'http: // localhost: 8080');
  };

  // Listen there is no data transmission over
  window.addEventListener ( 'message', 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 is no data transmission over
  window.addEventListener ( 'message', function (e) {
      // Determine whether the data sender is a reliable address
      if (e.origin ==! 'http: // localhost: 81')
        return;
    // Print data format
    console.log (e);
    // Postback data
    e.source.postMessage ( 'hello world', e.origin);
  }, False);
< / Script>

Red box marked are the three most important attributes, data by definition is a data transmission; origin is the source of the message window (URI protocol, host, port) to send; and reference source will be able to send a message window object (you can use send it to refer to the return message window).

In the end the listener can listen to the message reception event message (code above), of course, if you want to pit father compatible ie certainly use attachEvent. Here is not recommended window.onmessage, compatibility is not good (for example, not compatible with low version ff).

window < -> window
Having the same page with the iframe data exchange, come to talk about the data exchange between the two windows. We know that with window.open () to open a new window, and if the two windows homologous, the communication between the two windows will be very simple, we can window.opener.functionName call the original window in a new window methods (and variables). But if the two windows from different sources, such operations will become very difficult, fortunately H5 gives us postMessage, such window.opener.postMessage () without error! 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');

  /// When the popup has fully loaded, if not blocked by a popup blocker:
  setTimeout (function () {
      // The current window to the target data source Biography
    popup.postMessage ({ "age": 10}, 'http: // localhost: 8080');
  }, 1000);
< / Script>
 
 
< - Http:! // Localhost: 8080 / index.html ->
< Script type = "text / javascript">
  // Set the monitor, if there is data transmission over the print
  window.addEventListener ( 'message', function (e) {
    console.log (e);
    // Console.log (e.source === window.opener); // true
  });
< / Script>
To set a timer here because the target window to send data must wait for the target window has been completely loaded, the target window that is to be set up "listener" send window of data in order to be sent to the monitor, so give a timer delay, but because of the uncertainty of load time delay so the value of the timer can not be determined; another possible solution is finished when the target page is loaded, a message source page (postMessage), while income source page to the message, and then send the message to the target postMessage page.

Security concerns

Mentioned cross-domain data exchange, conditioned reflex will ask, safe? For postMessage, the answer is yes.

postMessage uses a "two-way security mechanism." When the sender sends data, it will confirm acceptance of the source side (it is best not to use *), and the recipient listens to the message after the event, it can be used to determine whether event.origin from the correct and reliable sender.
     
         
       
         
  More:      
 
- Gentoo: startx appeared Failed to load module Problem Solving (Linux)
- JSON Introduction and Usage Summary (Programming)
- Oracle table space create large files (Database)
- Linux Getting Started tutorial: hard disk partition and to deal with traps (Linux)
- Linux, ls command to achieve (Linux)
- Linux firewall settings instance (Linux)
- swap space is insufficient cause OOM kill MySQL Case (Database)
- Linux system - The understanding cpu load (Linux)
- After VMware CentOS full VM clone the network card is unavailable Solutions (Linux)
- ORA-12547: TNS: lost contact error Solution (Database)
- How to ensure the Linux SSH login security with one-time password (Linux)
- ActiveMQ-based shared file system HA solutions (Server)
- Use OpenSSL to generate a certificate detailed process (Linux)
- Linux, modify / retrieve the root password (Linux)
- Linux script commands - terminal recorder (Linux)
- JavaScript function part (Programming)
- Using Android Studio integrated development environment to build Android (Linux)
- Linux performance optimization tools perf top (Linux)
- Understand ASP.NET 5 running the command: DNVM, DNX, and DNU (Server)
- Zabbix monitoring tool deployment under Ubuntu server (Server)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.