window.postMessage across the window, across the iframe javascript communication

Homologous communication

Perform their page is in the same protocol (http / https), ports (80/443), the host (usually a domain name), the two scripts to communicate with each other

In most cases, the site is the internal domain name, it is homologous communication, access to each other

Non-homologous communication

Different domain names, different windows, embedded iframe (may be external domain name address) This is a non-homologous communication,

window.postMessage () method can be implemented safely across the source communication

From H5 api, did not expect it this way there is a h5 *. *

grammar

otherWindow.postMessage(message, targetOrigin, [transfer]);

  1. otherWindow  a reference to the other windows, such as an iframe contentWindow properties window.open execution window object returned, or name or numerical index over window.frames.

  2. message  to be transmitted to the data in the other window, strings, numbers and types of objects other basic javascript

  3. targetOrigin  to specify a window through which the window origin property can receive an event message, which may be a string "*" (unlimited) or a URI. When sending a message, if any protocol target window, the host address or port does not match one of these three values targetOrigin provided, then the message will not be sent; only three exact match, a message will be sent. This mechanism is used to control which messages can be sent to the window

usage

  1. send data
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input type="color" onchange="setMessage(this.value)">
<iframe id ='iframe' src="good.html"></iframe>

<script>
    // 发送消息
    var domain = 'http://localhost:63342';
    var iframe =  document.getElementById('iframe').contentWindow;

    var setMessage = function (color){
        iframe.postMessage(color,domain);
    }

    window.addEventListener('message',function(event){
        if(event.origin !== domain) return
        console.log('main receive ' + event.data);
    })
</script>
</body>
</html>
  1. Listen for events, process messages
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>good</title> </head> <body> <h1 style="text-align: center;color: black;">看我在便颜色</h1> </body> <script> // 响应消息 window.addEventListener('message',function(event){ if(event.origin !== 'http://localhost:63342') return; document.body.style.backgroundColor = event.data; document.body.innerHTML = event.data; event.source.postMessage('good idea ',event.origin); },false); </script> </html> 

Guess you like

Origin www.cnblogs.com/telwanggs/p/11289723.html