HTML5

Standardized since Oct 28, 2014

Semantic Tags

  • Tags describe your content
    • article
    • aside
    • progress
    • section
    • time
    • ...many more

Storage

localStorage & sessionStorage

  • Stores key-value pairs
  • Syncronous API, no callbacks
  • Works very similar to regular JS Objects
  • Stores in file, instead of memory

localStorage API

Setting Items


          localStorage.setItem("myKey", "myValue");

          // or

          localStorage.myKey = "myValue";
            

Getting Items


          var data = localStorage.getItem("myKey");

          // or

          var data = localStorage.myKey;
            

localStorage API

Removing Items


          localStorage.removeItem("myKey");

          // or

          delete localStorage.myKey;
            

Remove all Items


          localStorage.clear();
            

How many items?


          var length = localStorage.length;
            

What's the deal?

Session Storage Local Storage

Survives page refresh

Survives browser close

Short life span

Longer life span

  • Shopping carts
  • Breadcrumbs
  • Navigation history
  • Game high score
  • Search history
  • Access log

Stored client side. User can clear data.

Synchronous API. Blocks UI.

WebSQL

  • Traditional Database in browser
  • Exact same API as SQLite
  • Non-Standard
  • Firefox doesn't plan to support. Available in Chrome, Opera, Safari etc.

Indexed DB

  • Proposed Web Standard
  • Asynchronous API
  • Larger storage limit
    • Firefox: No upper limit. User prompt 50MB+
    • Chrome: 20% of shared temporary storage
  • NoSQL
  • Very Fast
  • Used heavily in Firefox OS
  • Firefox 16+ — Google Chrome 24+

Indexed DB

Connecting


          var request = window.indexedDB.open("MyDatabase");

          request.onerror = function(event) {
              console.log("failure");
          };

          request.onsuccess = function(event) {
              console.log("success");
              // now we can access the database
          };
          

Indexed DB

Retrieving Data


          var transaction = db.transaction(["customers"]);

          var objectStore = transaction.objectStore("customers");

          var request = objectStore.get("444-44-4444");

          request.onerror = function(event) {
            // Handle errors!
          };

          request.onsuccess = function(event) {
            // Do something with the request.result!
            alert("Name for SSN 444-44-4444 is " + request.result.name);
          };
          

Application Cache

  • Allows applications to run offline
  • Fetches assets. Stores locally
  • Browser no longer needs network
  • For offline, speed and less data use

App Cache, How to Use

Add manifest link to HTML


          <html manifest="example.appcache">
          ...
          

Add Manifest File


          CACHE MANIFEST
          # v1 - 2014-12-09
          # This is a comment.
          http://www.example.com/index.html
          http://www.example.com/header.png
          http://www.example.com/blah/blah
          

Online/Offline events

Check if online


          if (navigator.onLine) {
            // YAAAY, we have network!
          }
          

Handle Events


          window.addEventListener('online',  updateOnlineStatus);
          window.addEventListener('offline', updateOnlineStatus);
          

Drag & Drop

  • For on page elements
    • ex. WYSIWYG editing
  • From desktop
    • ex. uploading files
  • Many events, flexible
    • dragstart, dragover, dragleave
      drop, drag, dragend

Web Workers

  • JavaScript is Single-Threaded
  • Offload "work" to another thread
  • No shared memory
    • No access to window
    • Only pass "message"
  • Can perform network requests

Web Worker API


          var myWorker = new Worker("my_task.js");

          myWorker.addEventListener("message", function (oEvent) {
              console.log("Called back by the worker!\n");
          }, false);

          myWorker.postMessage(""); // start the worker.
          

Device Orientation & Motion

  • Detect rotation and movement
  • Accelerometer access
  • Experimental feature
    • Only in Chrome & Firefox
    • no plans for IE or Safari

Device Orientation Code


          window.addEventListener("deviceorientation", handleOrientation, true);

          function handleOrientation(event) {
            var absolute = event.absolute;
            var alpha    = event.alpha;
            var beta     = event.beta;
            var gamma    = event.gamma;

            // Do stuff with the new orientation data
          }
          

Geolocation

  • Standardized
  • Uses GPS/AGPS to get location coordinates.
  • Must ask permission

Geolocation API


          // find user position
          navigator.geolocation.getCurrentPosition(function(position) {
            console.log(position.coords.latitude);
            console.log(position.coords.longitude);
          });

          // watch user position, update as user moves
          var watchID = navigator.geolocation.watchPosition(function(position) {
              do_something(position.coords.latitude, position.coords.longitude);
          });
          

WebSockets

  • Exchange data between client & server
  • Continuous full-duplex connection stream
  • Uses the ws protocol
  • W3C Working Draft

WebSocket API


// Create connection
var mysocket = new WebSocket("ws://example.com/socketserver");

// Send data when connection has opened
mysocket.onopen = function () {
   mysocket.send("Hello, World!");
}

// Receive data from server
mysocket.onmessage = function (event) {
    console.log(event.data);
}
          

WebRTC

  • Real-Time Communications on the Web
  • P2P video-confering without plugins
  • Built into browsers
  • JavaScript based APIs
  • Used by Firefox Hello
  • Uses getUserMedia to grab video/audio

getUserMedia

Using getUserMedia


// Cross-browser
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia ||
                         navigator.webkitGetUserMedia;

navigator.getUserMedia({
    video: true,
    audio: true
}, function (localstream) {
    var vid = document.querySelector("video");
    vid.src = URL.createObjectURL(localstream);
    vid.play();
}, function (error) {
    console.log("Error occured in getUserMedia", error);
});
          

Other useful WebAPIs

  • Contacts
  • Notifications
  • Battery Status
  • Screen Orientation
  • ...check MDN WebAPIs page for more!

Questions?