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]);
-
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.
-
message to be transmitted to the data in the other window, strings, numbers and types of objects other basic javascript
-
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
- 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>
- 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>
This article from the creation, use of the Creative Commons Attribution 4.0 International License Agreement for licensing
Site articles except where noted reprint / source, both the original site or translated, reproduced, make sure the signature before
final editing time: 2019/05/16 16: 02