一、 postMessage
window.postMessage () method for enabling cross-communication between the source safely Window object; e.g., between pages and it generates pop-up windows, or in between pages and embedded therein iframe.
Second, grammar
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow: receiving an object reference to form, for example: subform (iframe) references to the parent form "window.parent" or other references Iframe "Window.frames + index (name or number)."
message: The data to be sent to the other window. In the following IE9 browser, message does not support JSON object must be of type string
targetOrigin: to specify which properties window via the window origin 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.
transfer: is a string and the simultaneous transmission of message Transferable
objects ownership of these objects will be transferred to the recipient of the message, the sender side will no longer retain ownership.
Communication between the three applications, and the parent form subform
1. parent.html: added Iframe (childIframe.html) page, and listen for message events
<html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title></title> <style> iframe{ border:none; width:100%; } </style> </head> <body> <>h1parent</h1> <iframe src="childiframe.html"></iframe> <script> window.addEventListener("message", function (message) { alert(JSON.stringify(message.data)); }); </script> </body> </html>
2. childIframe.html: sending a message directly to the parent
<html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title></title> </head> <body> <h1>childIframe</h1> <script> window.parent.postMessage({type:"open",url:"iframe.html"},"*"); </script> </body> </html>
3. IE9- compatibility issues:
IE9 and below the browser, message does not support JSON object must be a string type. When sending a string to convert JSON
window.parent.postMessage(JSON.stringify({ type: "open", url: "iframe.html" }), "*");
IE8 or IE9 is not compatible addEventListener and "message" listening methods, and events compatible way
//IE8,IE9兼容方法 if (window.attachEvent) { window.attachEvent('onmessage', function (message) { console.log(JSON.parse(message.data)); }); } else { window.addEventListener('message', function (message) { console.log(JSON.parse(message.data)); }); }