25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

116<br />

CHAPTER 5 ■ USING THE COMMUNICATION APIS<br />

To receive messages, you just have to add an event handler to your page. When a message arrives,<br />

you can check its origin and decide whether or not to do something with the message. Listing 5-1 shows<br />

an event listener that passes the message to a messageHandler function.<br />

Listing 5-1. An event listener for message events<br />

window.addEventListener(“message”, messageHandler, true);<br />

function messageHandler(e) {<br />

switch(e.origin) {<br />

case “friend.example.com”:<br />

// process message<br />

processMessage(e.data);<br />

break;<br />

default:<br />

// message origin not recognized<br />

// ignoring message<br />

}<br />

}<br />

A message event is a DOM event with data and origin properties. The data property is the actual<br />

message that the sender passed along and the origin property is the sender’s origin. Using the origin<br />

property, it is easy for the receiving side to ignore messages from untrusted sources; the origin can<br />

simply be checked against a list of allowed origins.<br />

As shown in Figure 5-1, the postMessage API provides a way to communicate between a chat widget<br />

iframe hosted at http://chat.example.net and an <strong>HTML</strong> page that contains the chat widget iframe<br />

hosted at http://portal.example.com (two different origins).<br />

Figure 5-1. postMessage communication between an iframe and a main <strong>HTML</strong> page

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!