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.

154<br />

CHAPTER 6 ■ USING THE <strong>HTML</strong>5 WEBSOCKET API<br />

Using the <strong>HTML</strong>5 WebSocket API<br />

In this section, we’ll explore the use of <strong>HTML</strong>5 WebSocket in more detail.<br />

Checking for Browser Support<br />

Before you use the <strong>HTML</strong>5 WebSocket API, you will want to make sure there is support in the browser<br />

for what you’re about to do. This way, you can provide some alternate text, prompting the users of your<br />

application to upgrade to a more up-to-date browser. Listing 6-9 shows one way you can test for browser<br />

support.<br />

Listing 6-7. Checking for browser support<br />

function loadDemo() {<br />

if (window.WebSocket) {<br />

document.getElementById("support").inner<strong>HTML</strong> = "<strong>HTML</strong>5 WebSocket is supported in your<br />

browser.";<br />

} else {<br />

document.getElementById("support").inner<strong>HTML</strong> = "<strong>HTML</strong>5 WebSocket is not supported in<br />

your browser.";<br />

}<br />

}<br />

In this example, you test for browser support in the loadDemo function, which might be called when<br />

the application’s page is loaded. A call to window.WebSocket will return the WebSocket object if it exists, or<br />

trigger the failure case if it does not. In this case, the page is updated to reflect whether there is browser<br />

support or not by updating a previously defined support element on the page with a suitable message.<br />

Another way to see if <strong>HTML</strong>5 WebSocket is supported in your browser, is to use the browser’s<br />

console (Firebug or Chrome Developer Tools for example). Figure 6-5 shows how you can test whether<br />

WebSockets is supported natively in Google Chrome (if it is not, the window.WebSocket command returns<br />

“undefined.”)<br />

Figure 6-5. Testing WebSocket support in Google Chrome Developer Tools

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

Saved successfully!

Ooh no, something went wrong!