- •Contents at a Glance
- •Contents
- •Foreword
- •About the Authors
- •About the Technical Reviewer
- •Acknowledgments
- •Introduction
- •Who This Book Is For
- •An Overview of This Book
- •Example Code and Companion Web Site
- •Contacting the Authors
- •Overview of HTML5
- •The Story So Far—The History of HTML5
- •The Myth of 2022 and Why It Doesn’t Matter
- •Who Is Developing HTML5?
- •A New Vision
- •Compatibility and Paving the Cow Paths
- •Utility and the Priority of Constituencies
- •Interoperability Simplification
- •Universal Access
- •A Plugin–Free Paradigm
- •What’s In and What’s Out?
- •What’s New in HTML5?
- •New DOCTYPE and Character Set
- •New and Deprecated Elements
- •Semantic Markup
- •Simplifying Selection Using the Selectors API
- •JavaScript Logging and Debugging
- •window.JSON
- •DOM Level 3
- •Monkeys, Squirrelfish, and Other Speedy Oddities
- •Summary
- •Using the Canvas API
- •Overview of HTML5 Canvas
- •History
- •What Is a Canvas?
- •Canvas Coordinates
- •When Not to Use Canvas
- •Fallback Content
- •CSS and Canvas
- •Browser Support for HTML5 Canvas
- •Using the HTML5 Canvas APIs
- •Checking for Browser Support
- •Adding a Canvas to a Page
- •Applying Transformations to Drawings
- •Working with Paths
- •Working with Stroke Styles
- •Working with Fill Styles
- •Filling Rectangular Content
- •Drawing Curves
- •Inserting Images into a Canvas
- •Using Gradients
- •Using Background Patterns
- •Scaling Canvas Objects
- •Using Canvas Transforms
- •Using Canvas Text
- •Applying Shadows
- •Working with Pixel Data
- •Implementing Canvas Security
- •Building an Application with HTML5 Canvas
- •Practical Extra: Full Page Glass Pane
- •Practical Extra: Timing Your Canvas Animation
- •Summary
- •Working with Scalable Vector Graphics
- •Overview of SVG
- •History
- •Understanding SVG
- •Scalable Graphics
- •Creating 2D Graphics with SVG
- •Adding SVG to a Page
- •Simple Shapes
- •Transforming SVG Elements
- •Reusing Content
- •Patterns and Gradients
- •SVG Paths
- •Using SVG Text
- •Putting the Scene Together
- •Building an Interactive Application with SVG
- •Adding Trees
- •Adding the updateTrees Function
- •Adding the removeTree Function
- •Adding the CSS Styles
- •The Final Code
- •Summary
- •Working with Audio and Video
- •Overview of Audio and Video
- •Video Containers
- •Audio and Video Codecs
- •Audio and Video Restrictions
- •Browser Support for Audio and Video
- •Using the Audio and Video API
- •Checking for Browser Support
- •Accessibility
- •Understanding Media Elements
- •Working with Audio
- •Working with Video
- •Practical Extras
- •Summary
- •Using the Geolocation API
- •About Location Information
- •Latitude and Longitude Coordinates
- •Where Does Location Information Come From?
- •IP Address Geolocation Data
- •GPS Geolocation Data
- •Wi-Fi Geolocation Data
- •Cell Phone Geolocation Data
- •User–Defined Geolocation Data
- •Browser Support for Geolocation
- •Privacy
- •Triggering the Privacy Protection Mechanism
- •Dealing with Location Information
- •Using the Geolocation API
- •Checking for Browser Support
- •Position Requests
- •Building an Application with Geolocation
- •Writing the HTML Display
- •Processing the Geolocation Data
- •The Final Code
- •Practical Extras
- •What’s My Status?
- •Show Me on a Google Map
- •Summary
- •Using the Communication APIs
- •Cross Document Messaging
- •Understanding Origin Security
- •Browser Support for Cross Document Messaging
- •Using the postMessage API
- •Building an Application Using the postMessage API
- •XMLHttpRequest Level 2
- •Cross-Origin XMLHttpRequest
- •Progress Events
- •Browser Support for HTML5 XMLHttpRequest Level 2
- •Using the XMLHttpRequest API
- •Building an Application Using XMLHttpRequest
- •Practical Extras
- •Structured Data
- •Framebusting
- •Summary
- •Using the WebSocket API
- •Overview of WebSocket
- •Real-Time and HTTP
- •Understanding WebSocket
- •Writing a Simple Echo WebSocket Server
- •Using the WebSocket API
- •Checking for Browser Support
- •Basic API Usage
- •Building a WebSocket Application
- •Coding the HTML File
- •Adding the WebSocket Code
- •Adding the Geolocation Code
- •Putting It All Together
- •The Final Code
- •Summary
- •Using the Forms API
- •Overview of HTML5 Forms
- •HTML Forms Versus XForms
- •Functional Forms
- •Browser Support for HTML5 Forms
- •An Input Catalog
- •Using the HTML5 Forms APIs
- •New Form Attributes and Functions
- •Checking Forms with Validation
- •Validation Feedback
- •Building an Application with HTML5 Forms
- •Practical Extras
- •Summary
- •Working with Drag-and-Drop
- •Web Drag-and-Drop: The Story So Far
- •Overview of HTML5 Drag-and-Drop
- •The Big Picture
- •Events to Remember
- •Drag Participation
- •Transfer and Control
- •Building an Application with Drag-and-Drop
- •Getting Into the dropzone
- •Handling Drag-and-Drop for Files
- •Practical Extras
- •Customizing the Drag Display
- •Summary
- •Using the Web Workers API
- •Browser Support for Web Workers
- •Using the Web Workers API
- •Checking for Browser Support
- •Creating Web Workers
- •Loading and Executing Additional JavaScript
- •Communicating with Web Workers
- •Coding the Main Page
- •Handling Errors
- •Stopping Web Workers
- •Using Web Workers within Web Workers
- •Using Timers
- •Example Code
- •Building an Application with Web Workers
- •Coding the blur.js Helper Script
- •Coding the blur.html Application Page
- •Coding the blurWorker.js Web Worker Script
- •Communicating with the Web Workers
- •The Application in Action
- •Example Code
- •Summary
- •Using the Storage APIs
- •Overview of Web Storage
- •Browser Support for Web Storage
- •Using the Web Storage API
- •Checking for Browser Support
- •Setting and Retrieving Values
- •Plugging Data Leaks
- •Local Versus Session Storage
- •Other Web Storage API Attributes and Functions
- •Communicating Web Storage Updates
- •Exploring Web Storage
- •Building an Application with Web Storage
- •The Future of Browser Database Storage
- •The Web SQL Database
- •The Indexed Database API
- •Practical Extras
- •JSON Object Storage
- •A Window into Sharing
- •Summary
- •Overview of HTML5 Offline Web Applications
- •Browser Support for HTML5 Offline Web Applications
- •Using the HTML5 Application Cache API
- •Checking for Browser Support
- •Creating a Simple Offline Application
- •Going Offline
- •Manifest Files
- •The ApplicationCache API
- •Application Cache in Action
- •Building an Application with HTML5 Offline Web Applications
- •Creating a Manifest File for the Application Resources
- •Creating the HTML Structure and CSS for the UI
- •Creating the Offline JavaScript
- •Check for ApplicationCache Support
- •Adding the Update Button Handler
- •Add Geolocation Tracking Code
- •Adding Storage Code
- •Adding Offline Event Handling
- •Summary
- •The Future of HTML5
- •Browser Support for HTML5
- •HTML Evolves
- •WebGL
- •Devices
- •Audio Data API
- •Touchscreen Device Events
- •Peer-to-Peer Networking
- •Ultimate Direction
- •Summary
- •Index
CHAPTER 6 USING THE COMMUNICATION APIS
Listing 6-8. Using the onprogress Event
crossOriginRequest.onprogress = function(e) { var total = e.total;
var loaded = e.loaded;
if (e.lengthComputable) {
// do something with the progress information
}
}
crossOriginRequest.upload.onprogress = function(e) { var total = e.total;
var loaded = e.loaded;
if (e.lengthComputable) {
// do something with the progress information
}
}
Binary Data
Browsers that support new binary APIs such as Typed Array (which is necessary for WebGL and programmable audio) may be able to send binary data with XMLHttpRequest. The XMLHttpRequest Level 2 specification includes support for calling the send() method with Blob and ArrayBuffer (aka Typed Array) objects (see Listing 6-9).
Listing 6-9. Sending a Typed Array of Bytes
var a = new Uint8Array([8,6,7,5,3,0,9]); var xhr = new XMLHttpRequest(); xhr.open("POST", "/data/", true) console.log(a)
xhr.send(a.buffer);
This makes an HTTP POST request with a binary content body. The content length is 7, and the body contains the bytes 8,6,7,5,3,0,9.
XMLHttpRequest Level 2 also exposes binary response data. Setting the responseType attribute to “text,” “document,” “arraybuffer,” or “blob” controls the type of object returned by the response property. To see the raw bytes contained by the HTTP response body, set the responseType to “arraybuffer” or “blob.”
In the next chapter, we’ll see how WebSocket can be used to send and receive binary data using the same types.
Building an Application Using XMLHttpRequest
In this example, we’ll look at uploading race geolocation coordinates to a web server hosted on a different origin. We use the new progress events to monitor the status of the HTTP request including the upload percentage. Figure 6-6 shows the application in action.
151
CHAPTER 6 USING THE COMMUNICATION APIS
Figure 6-6. A Web Application That Uploads Geolocation Data
For the sake of illustration, we’ve created the HTML file crossOrignUpload.html. The following steps highlight the important parts of building the cross-origin upload page shown in Figure 6-5. The sample code for the following examples is located in the code/communication folder.
First, create a new XMLHttpRequest object, as shown in the following example.
var xhr = new XMLHttpRequest();
Next, do check if cross-origin XMLHttpRequest is supported in the browser, as shown in the following example.
if (typeof xhr.withCredentials === undefined) { document.getElementById("support").innerHTML =
"Your browser <strong>doesnot</strong> support cross-origin XMLHttpRequest";
} else { document.getElementById("support").innerHTML =
"Your browser <strong>does</strong> support cross-origin XMLHttpRequest";
}
Next, set callback functions to handle the progress events and calculate the uploaded and downloaded ratios.
xhr.upload.onprogress = function(e) { var ratio = e.loaded / e.total; setProgress(ratio + "% uploaded");
}
xhr.onprogress = function(e) { var ratio = e.loaded / e.total;
setProgress(ratio + "% downloaded");
}
xhr.onload = function(e) { setProgress("finished");
}
152
CHAPTER 6 USING THE COMMUNICATION APIS
xhr.onerror = function(e) { setProgress("error");
}
Finally, open the request and send the string containing the encoded geolocation data. This will be a cross-origin request because the target location is a URL with a different origin than the page.
var targetLocation = "http://geodata.example.net:9999/upload"; xhr.open("POST", targetLocation, true);
geoDataString = dataElement.textContent; xhr.send(geoDataString);
The Final Code
Listing 6-10 shows the complete application code—the contents of the crossOriginUpload.html file.
Listing 6-10. Contents of crossOriginUpload.html
<!DOCTYPE html>
<title>Upload Geolocation Data</title> <link rel="stylesheet" href="styles.css">
<link rel="icon" href="http://apress.com/favicon.ico"> <script>
function loadDemo() {
var dataElement = document.getElementById("geodata"); dataElement.textContent = JSON.stringify(geoData).replace(",", ", ", "g");
var xhr = new XMLHttpRequest()
if (typeof xhr.withCredentials === undefined) { document.getElementById("support").innerHTML =
"Your browser <strong>does not</strong> support cross-origin XMLHttpRequest";
} else { document.getElementById("support").innerHTML =
"Your browser <strong>does</strong> support cross-origin XMLHttpRequest";
}
var targetLocation = "http://geodata.example.net:9999/upload";
function setProgress(s) { document.getElementById("progress").innerHTML = s;
}
document.getElementById("sendButton").addEventListener("click", function() {
xhr.upload.onprogress = function(e) { var ratio = e.loaded / e.total; setProgress(ratio + "% uploaded");
}
153
CHAPTER 6 USING THE COMMUNICATION APIS
xhr.onprogress = function(e) { var ratio = e.loaded / e.total;
setProgress(ratio + "% downloaded");
}
xhr.onload = function(e) { setProgress("finished");
}
xhr.onerror = function(e) { setProgress("error");
}
xhr.open("POST", targetLocation, true);
geoDataString = dataElement.textContent; xhr.send(geoDataString);
}, true);
}
window.addEventListener("load", loadDemo, true);
</script>
<h1>XMLHttpRequest Level 2</h1> <p id="support"></p>
<h4>Geolocation Data to upload:</h4> <textarea id="geodata">
</textarea>
</div>
<button id="sendButton">Upload</button>
<script>
geoData = [[39.080018000000003, 39.112557000000002, 39.135261, 39.150458, 39.170653000000001, 39.190128000000001, 39.204510999999997, 39.226759000000001, 39.238483000000002, 39.228154000000004, 39.249400000000001, 39.249533, 39.225276999999998, 39.191253000000003, 39.167993000000003, 39.145685999999998, 39.121620999999998, 39.095761000000003, 39.080593, 39.053131999999998, 39.02619, 39.002929000000002, 38.982886000000001, 38.954034999999998, 38.944926000000002, 38.919960000000003, 38.925261999999996, 38.934922999999998, 38.949373000000001, 38.950133999999998, 38.952649000000001, 38.969692000000002, 38.988512999999998, 39.010652, 39.033088999999997, 39.053493000000003, 39.072752999999999], [- 120.15724399999999, -120.15818299999999, -120.15600400000001, -120.14564599999999, - 120.141285, -120.10889900000001, -120.09528500000002, -120.077596, -120.045428, -120.0119, - 119.98897100000002, -119.95124099999998, -119.93270099999998, -119.927131, - 119.92685999999999, -119.92636200000001, -119.92844600000001, -119.911036, -119.942834, - 119.94413000000002, -119.94555200000001, -119.95411000000001, -119.941327, - 119.94605900000001, -119.97527599999999, -119.99445, -120.028998, -120.066335, - 120.07867300000001, -120.089985, -120.112227, -120.09790700000001, -120.10881000000001, - 120.116692, -120.117847, -120.11727899999998, -120.14398199999999]];
</script>
154