Game Development Reference
In-Depth Information
// ---------------------------------
var doc =
document.querySelector("iframe").contentWindow;
// alternatively:
// var doc =
window.open("web-messaging-rec.html", "",
"width=800,height=600");
// Post a message to the child document
doc.postMessage({msg: "Hello!"},
"http://localhost");
// --------------------------------------
// Child document: web-messaging-rec.html
// --------------------------------------
window.addEventListener("message",
function(event) {
var data = event.data;
// Post a message back to the parent document
event.source.postMessage({msg: "Thanks for
saying " + data.msg}, "*");
});
The first step to using the web messaging API is to get a reference to some doc-
ument with whom we wish to communicate. This can be done by getting the con-
tentWindow property of an iframe reference, or by opening a new window and
holding on to that reference. The document that holds this reference is called the
parent document, since this is where the communication is initiated. Although a child
window can communicate with its parent, this can only happen when and for as long
as this relationship holds true. In other words, a window cannot communicate with
just any window; it needs a reference to it, either through a parent-child relationship,
or through a child-parent relationship.
Once the child window has been referenced, the parent can fire messages to its
children through the postMessage function. Of course, if the child window hasn't
defined a callback function to capture and process the incoming messages, there is
little purpose in sending those messages in the first place. Still, the parent has no
way of knowing if a child window has defined a callback to process incoming mes-
sages, so the best we can do is assume (and hope) that the child window is ready to
receive our messages.
Search WWH ::




Custom Search