5 More HTML5 APIs You Didn’t Know Existed
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="https://davidwalsh.name/css-enhancements-user-experience" /> <!-- just an image --> <link rel="prefetch" href="https://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!
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.
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.
fantastic. Nice set of fun tools to try out. Thank you David.
Surely the Fullscreen API isn’t unknown these days: Youtube uses it!
Examples are simple, useful and awesome! Thanks!
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.
Looking forward to use these awesome API’s for my next web apps!!
Thanks David
Thanks David for such aWeSome POST!
nice, although I had those in mind, very nice list, my favorite goes for prefetch and getUserMedia
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! :)
The APIs are very useful but what about browser compatibility?
You can checkout caniuse.com
nice post, the page visibility only works when changing using keys, not clicking (chrome 24)
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
Thx David this is very interesting and useful, regards from spain.
Web MIDI: http://www.w3.org/TR/webmidi/
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/
Thank you. That was awesome especially the one for the battery.
it doesn’t look like the
canvas
andcontext
variables are used at all in thegetUserMedia
example code, however it is used in the demo.Nice tutorial, it’s first time I know its.
How about this, as a more concise version of the fullScreen request?
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.
Link Prefetching API was awesome…
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.
document.webkitFullscreenEnabled exists on chrome,but the document.webkitScreenEnabled is always false。
screenfull does a great job using the fullscreen API..
https://github.com/sindresorhus/screenfull.js
More Apis..
http://status.modern.ie/
Awesome one, Especially Page Visibility API, I was looking for something like this for long.
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 thatvar
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.Your code for getUserMedia defines ‘canvas’ and its ‘context’, but doesn’t use it…