O'Reilly

5 More HTML5 APIs You Didn’t Know Existed

By on  

The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a step in the right direction.  I recently shared with you 5 HTML5 APIs You Didn’t Know Existed in the hope that some of them would inspire you to improve your own web apps.  I'd like to share with you 5 more lessor known HTML5 APIs -- hopefully you find some of them useful!

Fullscreen API

The awesome Fullscreen API allows developers to programmatically launch the browser into fullscreen mode, pending user approval:

// Find the right method, call on correct element
function launchFullScreen(element) {
  if(element.requestFullScreen) {
    element.requestFullScreen();
  } else if(element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if(element.webkitRequestFullScreen) {
    element.webkitRequestFullScreen();
  }
}

// Launch fullscreen for browsers that support it!
launchFullScreen(document.documentElement); // the whole page
launchFullScreen(document.getElementById("videoElement")); // any individual element

Any element can be pushed to fullscreen, and there's even a CSS pseudo-class to allow some control over the screen while in fullscreen mode.  This API is especially useful for JavaScript game development;  especially first person shooters like BananaBread!

Page Visibility API

The Page Visibility API provides developers an event to listen in on, telling developers when the user focuses on a page's tab, and also when the user moves to another tab or window:

// Adapted slightly from Sam Dutton
// Set name of hidden property and visibility change event
// since some browsers only offer vendor-prefixed support
var hidden, state, visibilityChange; 
if (typeof document.hidden !== "undefined") {
  hidden = "hidden";
  visibilityChange = "visibilitychange";
  state = "visibilityState";
} else if (typeof document.mozHidden !== "undefined") {
  hidden = "mozHidden";
  visibilityChange = "mozvisibilitychange";
  state = "mozVisibilityState";
} else if (typeof document.msHidden !== "undefined") {
  hidden = "msHidden";
  visibilityChange = "msvisibilitychange";
  state = "msVisibilityState";
} else if (typeof document.webkitHidden !== "undefined") {
  hidden = "webkitHidden";
  visibilityChange = "webkitvisibilitychange";
  state = "webkitVisibilityState";
}

// Add a listener that constantly changes the title
document.addEventListener(visibilityChange, function(e) {
  // Start or stop processing depending on state

}, false);

When used properly, a developer can avoid expensive tasks (like AJAX polling or animating) when the tab isn't in focus.

getUserMedia API

The getUserMedia API is incredibly interesting;  this API provides access to device media, like your MacBook's camera!  Using this API, the <video> tag, and canvas, you can take beautiful photos within your browser!

// Put event listeners into place
window.addEventListener("DOMContentLoaded", function() {
  // Grab elements, create settings, etc.
  var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d"),
    video = document.getElementById("video"),
    videoObj = { "video": true },
    errBack = function(error) {
      console.log("Video capture error: ", error.code); 
    };

  // Put video listeners into place
  if(navigator.getUserMedia) { // Standard
    navigator.getUserMedia(videoObj, function(stream) {
      video.src = stream;
      video.play();
    }, errBack);
  } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
    navigator.webkitGetUserMedia(videoObj, function(stream){
      video.src = window.webkitURL.createObjectURL(stream);
      video.play();
    }, errBack);
  }
}, false);

Look forward to using this API quite a bit in the future -- interactivity within the browser will be the norm a year from now!

Battery API

The Battery API has been updated; read JavaScript Battery API Update to see the new code pattern!

The Battery API is obviously a mobile-targeted API providing insight into the device's battery level and status:

// Get the battery!
var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;

// A few useful battery properties
console.warn("Battery charging: ", battery.charging); // true
console.warn("Battery level: ", battery.level); // 0.58
console.warn("Battery discharging time: ", battery.dischargingTime);

// Add a few event listeners
battery.addEventListener("chargingchange", function(e) {
  console.warn("Battery charge change: ", battery.charging);
}, false);

Knowing battery API and status can signal to the web application not to use battery-intensive processes and the like.  Not a groundbreaking API but surely a helpful one.

Link Prefetching

Link prefetching allows developers to silently preload site contents to project a more fluid, seamless web experience:

<!-- full page -->
<link rel="prefetch" href="http://davidwalsh.name/css-enhancements-user-experience" />

<!-- just an image -->
<link rel="prefetch" href="http://davidwalsh.name/wp-content/themes/walshbook3/images/sprite.png" />

There's five more HTML5 APIs to research and tinker with.  Keep in mind that these APIs will be used widely in a few years, so the sooner you get acquainted with them, the better you'll be equipped to create world-class web applications.  Take a few moments to explore these APIs and see what you can put together!

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

  • Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

Incredible Demos

  • HTML5 Placeholder Styling with CSS

    Last week I showed you how you could style selected text with CSS. I've searched for more interesting CSS style properties and found another: INPUT placeholder styling. Let me show you how to style placeholder text within INPUTelements with some unique CSS code. The CSS Firefox...

  • TextboxList for MooTools and jQuery by Guillermo Rauch

    I'll be honest with you: I still haven't figured out if I like my MooTools teammate Guillermo Rauch. He's got a lot stacked up against him. He's from Argentina so I get IM'ed about 10 times a day about how great Lionel...

Discussion

  1. Manuel Manrique

    Nice post David
    Do you know which mobile browsers support the battery api? (Firefox only?)
    Thanks for the great post

    • The new version of Google Chrome also supports battery api. I think this came up a few days back.

  2. For the prefetch under chrome , there is the rel=prerender

    http://www.chromium.org/developers/design-documents/prerender

    https://developers.google.com/chrome/whitepapers/prerender

    No idea why they just didn’t call it “prefetch”

    • I believe Chrome does prefetching by default (although based on some heuristic). Also, “prerender” does much more than just prefetch a page. Apparently it also renders it and executes JS in the background.

  3. fantastic. Nice set of fun tools to try out. Thank you David.

  4. You Tube

    Surely the Fullscreen API isn’t unknown these days: Youtube uses it!

  5. GiN

    Examples are simple, useful and awesome! Thanks!

  6. Why do you refer to single function calls and single methods as “APIs”? There are function calls, and there are libraries containing function calls. Hint: the former isn’t the API.

  7. Looking forward to use these awesome API’s for my next web apps!!

    Thanks David

  8. Thanks David for such aWeSome POST!

  9. irrelevant

    nice, although I had those in mind, very nice list, my favorite goes for prefetch and getUserMedia

  10. Nice writeup David!

    @Carl: your definition of API may be a bit narrow for the JavaScript world. Unlike the classical oo world, we don’t necessarily correlate APIs with classes. We consider the properties (keys) of a configuration object to be an API. We consider the parameters of a single function to be an API. (Very often, a library or
    module only exposes a single function.)

    In that light, David’s definition of API feels normal to me! :)

  11. The APIs are very useful but what about browser compatibility?

    • bwaxxlo

      You can checkout caniuse.com

  12. Dreen

    nice post, the page visibility only works when changing using keys, not clicking (chrome 24)

  13. Allow me a shameless self-plug, but I wrote a tutorial-ish demo and the photobooth app you mentioned with getUserMedia() + video + HTML5 and I guess more than one reader, and possibly you, will find them interesting:

    Demo + tutorial-ish thing:
    https://github.com/cbrandolino/camvas

    Photobooth app:
    https://github.com/cbrandolino/camvas

  14. Bill

    Thx David this is very interesting and useful, regards from spain.

  15. Zecc

    Apologies if this comes out repeated, but my first comment seems to have been swallowed.

    There is also an API for using MIDI devices: http://www.w3.org/TR/webmidi/

    • fdgdfg
      if($type == 'rssfeed'){
      
          $feed_url = 'DBTutorBlog';
      
      	if (false === ($subscribers = get_transient('rss-subscribers-count'))) {
      		$feed_url = urlencode($feed_url);
      		$response = wp_remote_get("http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri={$feed_url}&dates=" . date('Y-m-d', strtotime('-2 days', time())).'&format=xml');
      
      		if (is_wp_error($response)) {
      			$subscribers = 97;
      		} else {
      			$body = wp_remote_retrieve_body($response);
      			@$xml = new SimpleXMLElement($body);
      
      			$status = $xml->attributes();
      
      			if ($status == 'ok') {
      				$subscribers = $xml->feed->entry->attributes()->circulation;
      			} else {
      				$subscribers = 98;
      			}
      		}
      
      		$subscribers = (int) $subscribers;
      		set_transient('rss-subscribers-count', $subscribers, 60*60*24);
      	}
      	echo $subscribers;
      }
      
  16. Ahwan.R

    Thank you. That was awesome especially the one for the battery.

  17. it doesn’t look like the canvas and context variables are used at all in the getUserMedia example code, however it is used in the demo.

  18. Nice tutorial, it’s first time I know its.

  19. David

    How about this, as a more concise version of the fullScreen request?

    function launchFS(e) {
         (e.requestFullScreen || e.mozRequestFullScreen || e.webkitRequestFullScreen).apply(de);
    }
    
  20. Great post! As browser support for HTML5’s many goodies improves, we will see the line between a web app and a “full desktop” experience blur beyond the point of where most end users’ won’t care how the experience is delivered to them. Just what devs really needed — less hassle and a leg up in productivity.

    getUserMedia() needs a bit more work, but it’s exactly the thing I’ve been looking forward for what seems like aeons.

    Cheers for the quick tutorial.

  21. Link Prefetching API was awesome…

  22. Stomme poes

    I remember when Firefox came out long ago prefetching. It was horrible: users who visited a page with hundreds of links found their surfing slow to a crawl as FF asked for links the user never had any intention to visit.

    For us, we needed a no-prefetch pragma in our sites because at the time we were using plain links to call our pages in other languages (we had a link to Portugues, a link to German, a link to French…) so it turned out screen reader users using Firefox ended up sitting in the last language in the list, which at the time was Portugues.

    Prefetching should be used with care and users who know they’re in crappy-bandwidth/crappy-connection land should have the ability to turn it off.

  23. Renfufei

    document.webkitFullscreenEnabled exists on chrome,but the document.webkitScreenEnabled is always false。

  24. rud

    screenfull does a great job using the fullscreen API..
    https://github.com/sindresorhus/screenfull.js

  25. Indrajeet Zala
  26. Awesome one, Especially Page Visibility API, I was looking for something like this for long.

  27. I like the examples and your code. Very interesting. One minor point of feedback: I think you should consider using multiple var statements instead of one in your JavaScript. Google’s JavaScript style guide says that var should always be used. A major selling point for this is that accidentally omitting a comma can introduce a variable into the global scope without producing an error.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Access Mac Camera by Command Line

    With all of my recent command line tutorials, I've really gotten excited about the shell's simplicity and realized the true power of using the underlying technology of pretty UIs.  Since I work from home, I spend a lot of time on video calls, so when...

  • Open Files from Command Line on OS X

    I'm as much of a fan of application UIs as anyone else but I'm finding myself working more and more from the command line lately.  Much of that is becoming obsessed with media manipulation but I'm forcing myself to use less UIs so that I...

  • Get Stock Quotes From Command Line

    When I conned my way into my first professional programming gig, I didn't really think much about money -- just that I was getting my foot in the door.  But as my career has gone on, I've been more aware of money, investing, and retirement.  I've recently...

  • Geolocation API

    One interesting aspect of web development is geolocation; where is your user viewing your website from? You can base your language locale on that data or show certain products in your store based on the user's location. Let's examine how you can...

  • Create an Image Preview from a Video

    Visuals are everything when it comes to media.  When I'm trying to decide whether to watch a video on Netflix, it would be awesome to see a trailer of some kind, but alas that isn't available.  When I'm looking to download a video on my computer,...