Game Development Reference
In-Depth Information
The parameters used in the
postMessage
function are fairly similar to the version
used in web workers. That is, any JavaScript value can be sent (numbers, strings,
Boolean values, object literals, and arrays, including typed arrays). If a function is
sent as the first parameter of
postMessage
(either directly, or as part of an ob-
ject), the browser will raise a
DATA_CLONE_ERR: DOM Exception 25
error. The
second parameter is a string, and represents the domain that we allow our message
to be received by. This can be an absolute domain, a forward slash (representing the
same origin domain as the document sending the message), or a wild card character
(*), representing any domain. If the message is received by a domain that doesn't
match the second parameter in
postMessage
, the entire message fails.
When receiving the message, the child window first registers a callback on the mes-
sage event. This function is passed a
MessageEvent
object, which contains the fol-
lowing attributes:
•
event.data
: It returns the data of the message
•
event.origin
: It returns the origin of the message, for server-sent
events and cross-document messaging
•
event.lastEventId
: It returns the last event ID string, for server-sent
events
•
event.sourceReturns
: It is the WindowProxy of the source window,
for cross-document messaging
•
event.portsReturns
: It is the MessagePort array sent with the mes-
sage, for cross-document messaging and channel messaging
Note
As an example of the sort of things we could use this feature for in the real world,
and in terms of game development, imagine being able to play our snake game,
but where the snake moves through a couple of windows. How creative is that?! Of
course, in terms of being practical, this may not be the best way to play a game, but
I find it hard to argue with the fact that this would indeed be a very unique and enga-
ging presentation of an otherwise common game.