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
- 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
- window.onload = function (e) {
- iframeElement = document.getElementById("my-iframe");
- // Parent postMessage.
- iframeElement.contentWindow.postMessage("ready", "http://examples.lingihuang.com")
- };
Receiving
Example
- var handleMessage = function (e) {
- if (e.origin !== "http://www.lingihuang.com") {
- return;
- }
- if (e.data === "ready") {
- // Child postMessage.
- //window.top.postMessage(size.width + "," + size.height, e.origin);
- e.source.postMessage(size.width + "," + size.height, e.origin);
- }
- };
- if (window.addEventListener) {
- window.addEventListener("message", handleMessage, false);
- } else {
- window.attachEvent("onmessage", handleMessage);
- }
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). |
回應 (Leave a comment)