Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ HTML5 postMessage cross-domain data exchange     - Expert advice: Do not use the computer security IE browser (Linux)

- Install Oracle JDK 8 and JVM class loading mechanism in Linux (Linux)

- CentOS Set the Mono environment variable (Server)

- Linux system file directory structure Introduction (Linux)

- Linux upgrade GCC 4.8.1 clear and concise tutorials (Ubuntu 12.04 64-bit version as an example) (Linux)

- Fedora 22 how to play rmvb mp4 mkv video files (Linux)

- Linux non-root user uses less than 1024 ports (Linux)

- Linux security configuration (Linux)

- Android determine the device network connection status, and determine the connection (Programming)

- Laravel 4.2 Laravel5 comprehensive upgrade Raiders (Server)

- Qt signals and slots mechanism (Programming)

- Android Fragment really fully resolve (Programming)

- CentOS boot image to achieve semi-automatic installation (Linux)

- Linux server operating system security configuration (Linux)

- How to configure AWStats in Ubuntu Server (Server)

- Python-- for anomalies and reflection of objects articles (Programming)

- ORA-30926 and MERGE tables empty the temporary occupation problem (Database)

- Kubernetes cluster deployment (Server)

- Generators and iterators in Python (Programming)

- Java Prototype Pattern (Programming)

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

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

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.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')
    // 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.
- CentOS-based Kickstart automated installation practice (Linux)
- Binary tree to the next node (Programming)
- Linux file time Comments ctime mtime atime (Linux)
- Linux system security knowledge (Linux)
- Linux operating system security settings initial understanding (Linux)
- CentOS 7 install Hadoop-cdh-2.5 on Mesos (Server)
- How to enable curl command HTTP2 support (Linux)
- Glibc support encryption by modifying the DNS (Programming)
- Install Git on CentOS (Linux)
- Neo4j map data processing tab (Database)
- Nginx reverse proxy and self-signed https (Server)
- CentOS install video converter FFmpeg and cutting tools segmenter (Linux)
- Configuration OpenOCD + FT2232 under Ubuntu (Linux)
- GO five stages of language learning (Programming)
- LogStash log analysis display system (Linux)
- Openfire Hazelcast cluster Detailed (Server)
- How to implement Linux host Telnet SSH password Free (Server)
- Build ftp server under CentOS 6.5 (Server)
- C / C ++ various data types Conversion Summary (Programming)
- To install Ganglia configuration of experience under CentOS 5.5 (Linux)
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.