2014
Mar
25




The postMessage API is supported by all modern browsers including IE8. It allows windows/frames from multiple domains to communicate with each other. IE8 doesn't allow to postMessage to other windows, only to iframes.

Cross-window messaging security model is two-sided. The sender ensures that the receiving domain is targetDomain. The receiver checks that the message came from proper event.origin.

Sending

postMessage Syntax
  1. window.postMessage(data, targetDomain);
Parameter Description
data The message. Accordin to the specification, it could be any object. But as of now, only strings are supported in major browsers.
targetDomain Limit receiving iframe by given domain. Can contain "*" which doesn't put any restrictions.
Example
  1. window.onload = function (e) {
  2. iframeElement = document.getElementById("my-iframe");
  3. // Parent postMessage.
  4. iframeElement.contentWindow.postMessage("ready", "http://examples.lingihuang.com")
  5. };

Receiving

Example
  1. var handleMessage = function (e) {
  2. if (e.origin !== "http://www.lingihuang.com") {
  3. return;
  4. }
  5.  
  6. if (e.data === "ready") {
  7. // Child postMessage.
  8. //window.top.postMessage(size.width + "," + size.height, e.origin);
  9. e.source.postMessage(size.width + "," + size.height, e.origin);
  10. }
  11. };
  12.  
  13. if (window.addEventListener) {
  14. window.addEventListener("message", handleMessage, false);
  15. } else {
  16. window.attachEvent("onmessage", handleMessage);
  17. }
Parameter Description
data The object passed from the other window. The first argument of postMessage.
origin The source domain.
source A reference to the window object that sent the message. It is possible to respond by calling event.source.postMessage("response message", event.origin).

View Demo

Related Post


回應 (Leave a comment)