25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Download from Wow! eBook <br />

122<br />

CHAPTER 5 ■ USING THE COMMUNICATION APIS<br />

Next, add a function to communicate with the chat widget. It uses postMessage to send a status<br />

update to the widget iframe contained in the portal page. In a live chat application, it could be used to<br />

communicate the user’s status (available, away, and so on).<br />

function sendString(s) {<br />

document.getElementById("widget").contentWindow.postMessage(s, targetOrigin);<br />

}<br />

Building the Chat Widget Page<br />

First, add an event listener messageHandler to listen for message events coming from the portal page. As<br />

shown in the following example code, the chat widget listens for incoming status-change messages. To<br />

make sure the message comes from the portal page, the message’s origin is verified; if it does not come<br />

from http://portal.example.com:9999, the widget simply ignores it.<br />

var targetOrigin = "http://portal.example.com:9999";<br />

function messageHandler(e) {<br />

if (e.origin === "http://portal.example.com:9999") {<br />

document.getElementById("status").textContent = e.data;<br />

} else {<br />

// ignore messages from other origins<br />

}<br />

}<br />

Next, add a function to communicate with the portal page. The widget will ask the portal to notify<br />

the user on its behalf and uses postMessage to send a message to the portal page when a new chat<br />

message is received, as shown in the following example:<br />

function sendString(s) {<br />

window.top.postMessage(s, targetOrigin);<br />

}<br />

The Final Code<br />

Listing 5-3 shows the complete code for the Portal page postMessagePortal.html.<br />

Listing 5-3. Contents of postMessagePortal.html<br />

<br />

Portal [http://portal.example.com:9999]<br />

<br />

<br />

iframe {<br />

height: 400px;<br />

width: 800px;<br />

}<br />

<br />

<br />

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

Saved successfully!

Ooh no, something went wrong!