HTML5 Doctor » JavaScript APIs http://html5doctor.com helping you implement HTML5 today Wed, 02 Mar 2016 08:08:54 +0000 en-US hourly 1 The Web Manifest specification https://stevefaulkner.github.io/html5doctored/web-manifest-specification/ https://stevefaulkner.github.io/html5doctored/web-manifest-specification/#comments Tue, 29 Jul 2014 09:51:22 +0000 http://html5doctor.com/?p=5515

Related Posts:

]]>
By Marcos Cáceres and Bruce Lawson.

Update 26 September 2014 The initial work for Manifest in Chromium M39 is done, and Marcos (more or less) finished coding the processor a few months ago. “I’m hoping to see it in fxos 2.2“, he said from the pool of his gorgeous Malibu home.)

Update 11 November 2014 Web Application Manifest is in Chrome 38.

Update 9 April 2015 Updated implementation status to note App Install banners in Chrome, Opera Android implementation underway. Also show how to link to the manifest (thanks @mathias!) and remove some scary “this may all change” warnings.

Update 18 August 2015 François Beaufort pointed out that “According to the spec https://w3c.github.io/manifest/#h-density-member, the density should actually be a number (not a string)” – amended accordingly.

Update 7 December 2015 Link to my blogpost declaring Progressive Web Apps “ready for primetime”; remove stuff about service_worker manifest member, as it’s gone now because it was useless

Manifest? Eh? What? Why?

Many of us who work on the web are actively working to narrow “the gap” between native applications and web applications. (Disclosure: your humble authors, Marcos Caceres and Bruce Lawson work for browser vendors – Mozilla and Opera respectively – and therefore have mortgage-related reasons to convince you this stuff is a good idea.)

But what is that gap? Just a few years ago, that gap was largely technological. If you wanted access to a device’s GPS, you had to write a native app. Nowadays, the situation is improving somewhat: we can now access devices sensors like GPS, camera, and orientation sensors – though we still have a long way to go. Thanks to recent advances in the web platform we now have a platform that can compete with native applications on a more equal footing.

Nowadays, the primary gaps between native and web is not so much technological. It’s user experience. Users simply love installing apps, which live snugly on the homescreen (or the desktop) waiting to be tickled into life with the tap of a finger or the click of a mouse.

Furthermore, native apps work offline by default, and integrate with the facilities provided by the underlying operating system: consider being able to see installed applications in the task switcher. Or being able to control an app’s privacy settings in the same place as apps installed from an app store. In browser land, we are still fumbling around trying to find opened tabs and having to type long and boring URLs to get anything done.

What we need is a method of “installing” web apps so they are indistinguishable from any other app installed on a user’s device. But at the same time, we don’t want to lose the powerful features that are central to the web platform: linkability, view source, and the ability to host our own stuff.

What is “installation”?

At its most basic, “installation” of a web app means “bookmarking” the web application to the homescreen or adding it to an application launcher. There are some pretty obvious things that you, as a developer, would need to provide to the browser so that it can treat your website as an app: the name, icons, etc. There are then more advanced features that you would need, like being able to indicate the preferred orientation and if you want your app to be fullscreen.

The Manifest specification aims to give you a standardised way to do this using JSON. In the HTML page to be “installed”, simply link to a manifest file, thus:

<link rel="manifest" href="/manifest.json">

But what’s in this mysterious manifest file? Glad you asked!

Application name

The application needs a real name or set of names (which is usually not the same as the title element of a document). For this you use the name and the short_name properties.

{
name: “My totally awesome photo app”
short_name: “Photos”
}

The short_name serves as the name for the application when displayed in contexts with constrained space (e.g., under an icon on the homescreen of a phone). The name can then be a bit longer, fully capturing the name of the application. This also provides an alternative way for users to search your app on their phone. So, typing ‘awesome’ or ‘photo’ would find the application on a user’s device.

If you omit the name, the browser just falls back to using <meta name=”application-name”>, and failing that, the <title> element.

Icons

There needs to be an icon associated with a web app, rather than the browser’s icon. To handle this, the manifest has an icons property. This takes a list of icons and their sizes, format, and target screen density. Having these optional properties makes icon selection really powerful, because it provides a responsive image solution for icons – which can help avoid unnecessary downloads and helps to make sure your icons always look great across a range of devices and screen densities.

{
   "icons": [{
        "src": "icon/lowres",
        "sizes": "64x64",
        "type": "image/webp"
      }, {
        "src": "icon/hd_small",
        "sizes": "64x64"
      }, {
        "src": "icon/hd_hi",
        "sizes": "128x128",
        "density": 2
      }]
}

If you omit the icons, the browser just falls back to looking for <link rel=”icon”>, the favicon.ico or, failing that, may even use a screenshot of your website.

Display modes and orientation

Apps need to be able to control how they are to be displayed when they starts-up. If it’s a game, it might need to be in full-screen and possibly in landscape mode. In order to do this, the manifest format provides you with two properties.

{
 "display": "fullscreen",
 "orientation": "landscape"
}

For the display modes, the options that you have are:

  • fullscreen: take over the whole screen.
  • standalone: opens the app with a status bar.
  • minimal-ui: like on iOS, the app is fullscreen, but certain actions can cause the navigation bar and back/forward buttons to reappear.
  • browser: opens your app with normal browser toolbars and buttons.

The nice thing with orientation is that it serves as the “default orientation” for the scope of the application. So, as you navigate from one page to another, your app stays in the correct orientation. You can override the default orientation using the Screen Lock API.

Start URL

Sometimes you want to make sure that when the user starts up an app, they always go to a particular page first. The start_url property gives you a way of indicating this.

{
 start_url: “/start_screen.html”
}

“Scope” of the app

Native applications have clear “boundaries”: as a user, you know when you open a native application that it won’t suddenly open a different application without you noticing. When switching from one native application to another is often pretty clear that you’ve switched applications. These visual cues are often provided by the underlying operating system (think of bringing up the task manager and picking a different application – or pressing “command/alt-tab” on your desktop machine).

The web is very different: it’s a huge hypertextual system where web applications can span multiple domains: you can seamlessly jump from “gmail.com” to “docs.google.com” and as a user have no idea that you’ve jumped form one “origin” to another. In fact, the whole idea that there are boundaries to an application is totally foreign on the Web as, in reality, a web application is just a series of HTML documents (think, “a series of tubes”… no, don’t think that!).

On the web, the only reason we know that we’ve left the scope of one application and entered into another application is because the web designers have been kind enough to make their websites look uniquely different. In case where they haven’t, a lot of users have also been tricked by sites masquerading as another site (the ol’ “phishing attack”).

The manifest format assist with this problem by allowing you to specify a “URL scope” for your application. This scope sets a boundary for an app. It can either be a domain or a directory within that domain.

{
    “scope”: “/myapp”
}

How can I detect if the user “installed” my app?

As a developer, you really should not have to worry about this – the browser will take care of it for you. Firstly, bugging users to install your app is annoying. We’ve all seen this happen in iOS with sites asking users to “add my app to the homescreen”.

Instead, the approach that we take with the manifest is that “installing” is a progressive enhancement. Focus on creating the optimum experience based on what “display mode” the application is in. You will be able to detect and style this with CSS.

@media all and (display-mode: standalone){ ...}

You can use JavaScript matchMedia to test that media query in JavaScript.

Addendum June 2015: In Chromium, you can detect whether a user accepted or dismissed an install banner.

What’s wrong with <meta> tags?

During the specification discussions, it was hotly debated whether to use <meta> tags in HTML rather than make a new format. After all, the Chrome implementation of Add to Homescreen uses <meta> tags, and this has been the natural home for proprietary flimflam since the web began.

The reasons for including a separate file are

  • it saves loading every page of an installable app/site with tons of header info
  • once downloaded, the file sits in the browsers’s HTTP cache.
  • Marcos loves JSON because he’s totally rad

Who is implementing this

The manifest, and Progressive Web Apps are implemented in Chrome and Opera for Android. Implementation is underway in Firefox. You can kinda-sorta do this is a non-standard way in Safari/iOS, too.

Progressive Web Apps are ready for primetime, I believe.

The Web Manifest specification originally appeared on HTML5 Doctor on July 29, 2014.

]]>
https://stevefaulkner.github.io/html5doctored/web-manifest-specification/feed/ 6
The classList API https://stevefaulkner.github.io/html5doctored/the-classlist-api/ https://stevefaulkner.github.io/html5doctored/the-classlist-api/#comments Tue, 30 Jul 2013 13:30:56 +0000 http://html5doctor.com/?p=5206 I have to be honest with you: I feel like a fraud writing about JavaScript for HTML5 Doctor. I would feel like a fraud writing about JavaScript for a click-driven ad-splattered content farm, never mind HTML5 Doctor. The thing is though, I'm writing about the classList API, and it's super easy. If your JavaScript-fu isn't great and you're wary of HTML5 APIs, this one is at the perfect temperature for toe-dipping, and it'll leave you pleasantly surprised at just how easy it is.

]]>
I have to be honest with you: I feel like a fraud writing about JavaScript for HTML5 Doctor. I would feel like a fraud writing about JavaScript for a click-driven ad-splattered content farm, never mind HTML5 Doctor.

The thing is though, I’m writing about the classList API, and it’s super easy. If your JavaScript-fu isn’t great and you’re wary of HTML5 APIs, this one is at the perfect temperature for toe-dipping, and it’ll leave you pleasantly surprised at just how easy it is.

The classList API is a “does exactly what it says on the tin” API. It gets a list of the classes on an HTML element and uses JavaScript to manipulate it.

Before this nugget of HTML5 came along, working with classes was a royal pain, but what was once a twisty overgrown cowpath with wolves lurking in thickets is now a bright sunlit path fit for rollerskating.

Getting the classList

Getting the classList is a simple matter of element.classList, like so:

<p id="bad-joke" class="oh my giddy aunt">Two dogs are in the park. One says, "Nice day, isn't it?" The other says, "Holy crap, a talking dog!"</p>

<script>
    var joke = document.getElementById('bad-joke');
    console.log(joke.classList);
</script>

That will log something like ["oh", "my", "giddy", "aunt"]. The output style varies between browsers, but it will be an object containing a list of the classes on the element.

More accurately, it’s an object that stringifies to the value of the class attribute on the element in question. Try it yourself with the console open.

{
    0: "oh",
    1: "my",
    2: "giddy",
    3: "aunt"
}

There is no specification for classList per se (it gets a sentence in the DOM4 spec), but there is for DOMTokenList, which is classList‘s type, so look at the DOMTokenList specification to find out how to work with lists of classes.

The Type of classList

If you’re looking to confirm the type of classList, you’ll need to do element.classList instanceof DOMTokenList, which returns true. typeof element.classList returns “object”, which, given that everything in JavaScript is an object, isn’t particularly informative.

Doing Things with our List of Classes

The DOMTokenList spec provides a number of methods that can be used on the classList:

  • add() for adding a class to the list
  • remove() for removing a class from the list
  • contains() to check if a class is in the list
  • toggle() for toggling a class in and out of the list (with a twist)
  • item() to return the class at a specified position in the list
  • toString() for turning the list into a string
  • length to return the number of classes in the list
  • value to add custom properties and methods to the classList object

classList.add()

It couldn’t be easier to add a class to an element. Just supply the class you want to add as an argument to the add() method.

joke.classList.add('beryl');

If you view the demo and look at the opening <p> tag in your favourite inspector before and after pressing the button, you’ll see it change from <p id="bad-joke" class="oh my giddy aunt"> to <p id="bad-joke" class="oh my giddy aunt beryl">.

Adding a class to the <p> is all done with that one line. No need to inject inline styles or anything messy like that.

The corresponding classList object is:

{
    0: "oh",
    1: "my",
    2: "giddy",
    3: "aunt",
    4: "beryl"
}

classList.remove()

Removing a class is just as easy. joke.classList.remove('beryl') brings us back to where we started.

View demo.

Adding and Removing Multiple Classes

The DOMTokenList spec refers to “tokens”, plural when describing how the add() and remove() methods should be run.

The add(tokens…) method […] If one of tokens is the empty string […] If one of tokens contains any ASCII whitespace […] For each token in tokens

No browser so far has implemented a native method of adding/removing more than one class at a time, but it’s trivial to extend the DOMTokenList object prototype with a hand rolled function:

It’s possible to add and remove multiple classes in the Blink powered browsers with element.classList.add('oh','my'), and it’s trivial to extend the DOMTokenList object prototype with a hand rolled function until support is more widespread:

Thanks to David and Kalley for pointing that out in the comments.

DOMTokenList.prototype.addmany = function(classes) {
    var classes = classes.split(' '),
        i = 0,
        ii = classes.length;

    for(i; i<ii; i++) {
        this.add(classes[i]);
    }
}

Same goes for remove:

DOMTokenList.prototype.removemany = function(classes) {
    var classes = classes.split(' '),
        i = 0,
        ii = classes.length;

    for(i; i<ii; i++) {
        this.remove(classes[i]);
    }
}

Here’s a demo where you can add and remove multiple classes at once.

A bug was filed in 2011 (against a document that no longer exists) suggesting allowing a space separated list or an array in classList.add() and classList.remove().

The use of the plural “tokens” could be interpreted as allowing an array, but it doesn’t work. InvalidCharacterError is still specified as the exception to throw if there are any spaces in “tokens”, so that’s definitely not going to work.

If you want to replace an entire classList with a completely different set of classes, you could use these two functions.

classList.contains()

This method returns a Boolean true or false when checking for the presence of a class in the list.

In our example:

joke.classList.contains('aunt') === true;
joke.classList.contains('uncle') === false;

contains() is useful for checking if a class is in a list before performing an action that depends on its presence (or otherwise):

if(joke.classList.contains('beryl') {
    joke.classList.remove('beryl');
}

We can use contains() to make our previous functions for adding and removing multiple classes better by ensuring they do not try to add duplicate classes on the element or remove classes that don’t exist on it:

DOMTokenList.prototype.addmany = function(classes) {
    var classes = classes.split(' '),
        i = 0,
        ii = classes.length;

    for(i; i<ii; i++) {
        if(!this.contains(classes[i])) {
            this.add(classes[i]);
        }
    }
}

and:

DOMTokenList.prototype.removemany = function(classes) {
    var classes = classes.split(' '),
        i = 0,
        ii = classes.length;

    for(i; i<ii; i++) {
        if(this.contains(classes[i])) {
            this.remove(classes[i]);
        }
    }
}

classList.toggle()

For most use cases, classList.toggle() is very straightforward too. Typically, an action by the program or the user will trigger a function that adds or removes a class depending on whether it’s already in the list.

A simple show/hide is a good example of this:

button.addEventListener('click', function() { element.classList.toggle('is-visible'); }, false);

View a demo of a two-level menu that takes up a little less room in smaller viewports by using classList.toggle() to enhance sub-menus.

force

There’s a little twist to toggle(), though. It can take an optional second parameter, force.

If force is set to true, the class will be added but not removed. If it’s false, the opposite will happen — the class will be removed but not added.

Now that sounds a lot like add() and remove(), but there is a crucial difference: toggle() with force returns true when a class is added, and false when it’s removed — add() and remove() return undefined.

At the time of writing, only the Blink powered browsers honour the force parameter, so view the demo with true and the demo with false in Opera 15, Opera for Android, or the latest Chrome to see it working.

Browsers that don’t support force completely ignore it and merrily toggle the class name on and off without throwing exceptions.

When it’s more widely supported, we can use a slightly leaner syntax for ensuring the presence or absence of a class in the list. Instead of:

var foo = function() {
    joke.classList.add('beryl');
}

foo();

if(joke.classList.contains('beryl')) {
    // do stuff
}

we could write:

var foo = function() {
    return joke.classList.toggle('beryl', true);
}

if(foo()) {
    // do stuff
}

classList.item()

The item() method can be found elsewhere in JavaScript, usually on NodeList objects. It returns the value of the item at index counting from zero.

In our example:

<div id="bad-joke" class="oh my giddy aunt">
    <p>"Knock knock."</p>
    <p>"Come on in, the door's open."</p>
</div>

<script>
    var joke = document.getElementById('bad-joke'),

        whats_item_0 = function() {
            return joke.classList.item(0);
        },

        whats_item_2 = function() {
            return joke.classList.item(2);
        };

    console.log(whats_item_0()); // logs "oh"
    console.log(whats_item_2()); // logs "giddy"
</script>

View the demo.

classList.item() cannot be used for assignment, so joke.classList.item(3) = 'uncle' will throw an error.

If you were hoping classList.item() could assign values to items at specific positions in the list, I’m afraid you’ll be disappointed. There’s no DOMTokenList method that gives that level of control over the list.

classList.toString()

If you ever need the classList turned into a string use this method. toString() is another built in JavaScript method that isn’t specific to DOMTokenList.

All the W3C spec says on the subject is that DOMTokenList objects must stringify to the underlying string. WHATWG leaves it at The stringifier must return the result of the set serializer for the associated list of tokens.

The only difference between the two is the amount of plain English used.

It takes no parameters when used with classList and returns all the classes on the element as a space separated string:

joke.classList.toString();
// returns "oh my giddy aunt";

classList.length

length is also a built-in JavaScript property. It returns the number of characters in a string, the number of items in an array, the number of arguments expected in a function, or (in our case) the number of classes in classList. In our example using “oh my giddy aunt”, it’s 4.

joke.classList.length
// returns 4

Simple and obvious, hopefully.

classList.value

On their own, the item(), toString(), and length methods aren’t especially useful. They can, however, be used in conjunction with each other and the rest of the methods of DOMTokenList to solve some of the problems I mentioned earlier.

Remember that classList is a regular JavaScript object, so we can add properties to it the same as any other object:

classList.use_in_production = false;
classList.id = 5;
classList.roof = 'thatch';

And of course we can add methods. Here’s a method that replaces the entire list with a new one using length, toString(), add(), and remove():

element.classList.replace = function(classes) {
    var i = 0,
        ii = this.length,
        old_string = this.toString(),
        old_array = old_string.split(' '),
        new_array = classes.split(' '),
        j = 0,
        jj = new_array.length;

    // remove all the existing classes
    for(i; i<ii; i++) {
        this.remove(old_array[i]);
    }

    // add the new ones
    for(j; j<jj; j++) {
        this.add(new_array[j]);
    }
};

And here’s a method that inserts a class in any position in the list you want. It uses contains(), item(), remove(), toString(), and the replace() method we just made:

element.classList.insert = function(insert,position) {
    // check if the class is already in classList
    if(this.contains(insert)) {
        if(this.item(position) === insert) {
            // if it is already at the right position there's no need to continue
            return;
        } else {
            // remove it, we don't want it here
            this.remove(insert);
        }
    }

    var classes = this.toString(),
        classes_array = classes.split(' ');

        classes_array.splice(position, 0, insert);

        new_list = classes_array.join(' ');

        // use the custom replace method to replace the current classList
        this.replace(new_list);
};

Being realistic, methods like these would probably be better used to extend DOMTokenList like we did with addmany() and removemany(), but if you ever need something specific to a particular classList you’re working on, you can use value.

Browser Support and Polyfills

The classList API works in pretty much every up-to-date browser version. Basic support at least has been in since Firefox 3.6, Opera 11.50, Chrome 8, and Safari 5.1.

The big holes are IE9 and earlier and the still widely used Android 2.3 and earlier.

There are at least two polyfills available that can fill these holes.

Devon Govett’s was written quickly to add support to IE9 only, and it’s worth reading the comments for some good cross-browser JavaScript info.

Eli Grey’s polyfill has wider browser support. It works in IE8, and it provides basic classList.add(), classList.remove(), and classList.toggle() support to at least as far back as Android 2.1.

There’s also a polyfill for adding force support by Егор Халимоненко to browsers that support classList but not force on toggle().

If you only need a simple feature test you can use:

if('classList' in document.createElement('a')) {
    // use classList API
}

Summary

You can think of the classList API on two levels. For most uses, it’s a simple way to add, remove, toggle, and check for the presence of single classes in an HTML element. I use it in every project I work on now and very rarely need to stray beyond these basic methods. I can’t think of any use for item(), length, or toString() as stand-alone methods, so don’t fret about them.

On another level, it’s about objects, it’s about finding powerful ways to manipulate the state of web pages, it’s about separation of concerns, it’s about progressive enhancement.

How far you take it is up to you, but as I said at the start, it’s an easy one to get into and makes what was hard, easy. I encourage you to take what I’ve written here and experiment in your own projects if you’re new to it, and take to the comments to tell me where I could have said it better if you’re already familiar with it.

Thank you!

The classList API originally appeared on HTML5 Doctor on July 30, 2013.

]]>
https://stevefaulkner.github.io/html5doctored/the-classlist-api/feed/ 18
Taking Web Audio Offline in iOS 6 Safari https://stevefaulkner.github.io/html5doctored/taking-web-audio-offline-in-ios-6-safari/ https://stevefaulkner.github.io/html5doctored/taking-web-audio-offline-in-ios-6-safari/#comments Tue, 27 Nov 2012 13:30:20 +0000 http://html5doctor.com/?p=4812

Related Posts:

]]>
Playing cached audio for offline use on iOS Safari has long been a challenge that has proved to be mission impossible. But with the advent of the (WebKit-only) Web Audio API, it is now finally achievable — although you still need to jump through a few hoops.

The bad news is that you still can’t cache an MP3 file using Application Cache and then simply load it using an XmlHttpRequest. Safari on iOS 6 will cache the MP3 but then refuse to play it and fail silently (how useful!).

But all is not lost…

Base64 to the Rescue

Because the Web Audio API offers developers direct control over the AudioBuffer, you can now convert data formats on-the-fly and feed them directly to the Web Audio API for playback. For example, if you encode an MP3 file as a Base64 string, you can then decode it to an ArrayBuffer and convert the raw audio data.

Encoding an Audio File

You can easily convert an MP3 file to a Base64 string using OpenSSL. If you are on Mac OS X, it comes pre-installed, so just open up Terminal.app and type the following command:

openssl base64 -in [infile] -out [outfile]

Make sure to replace [infile] with the path to your MP3 and [outfile] with your chosen destination for the encoded data.

This will output a Base64-encoded string representation of your sound file. You can then cache the string using any form of web storage you choose (e.g., Application Cache, localStorage, or webSQL).

Base64 to ArrayBuffer

In order to decode the Base64 string back into an ArrayBuffer, you’ll need to use a custom method. Check out Daniele Guerrero’s base64-binary.js as a good script that can be used exactly for this purpose. It decodes a Base64 string into a Uint8Array typed array and stores it in an ArrayBuffer.

Once this is done, you can simply decode the audio data using the Web Audio API’s decodeAudioData() method:

var buff = Base64Binary.decodeArrayBuffer(sound);

myAudioContext.decodeAudioData(buff, function(audioData) {
  myBuffer = audioData;
});

Once you have the audio data decoded, pass it to your audio buffer source and play the sound:

mySource = myAudioContext.createBufferSource();
mySource.buffer = myBuffer;
mySource.connect(myAudioContext.destination);
mySource.noteOn(0);

Full Demo and Source Code

Check out the online demo and source code for a complete example of the techniques discussed in this article.

Browser Support

Currently the demo works in Safari 6, Chrome Desktop, and iOS 6 Safari. The technique has potential to work in any browser that supports Web Audio API, so hopefully Chrome Mobile can soon add support as well.

The W3C is currently pursuing the Web Audio API as a standard.

Taking Web Audio Offline in iOS 6 Safari originally appeared on HTML5 Doctor on November 27, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/taking-web-audio-offline-in-ios-6-safari/feed/ 11
HTML5 Audio — The State of Play https://stevefaulkner.github.io/html5doctored/html5-audio-the-state-of-play/ https://stevefaulkner.github.io/html5doctored/html5-audio-the-state-of-play/#comments Tue, 08 May 2012 14:00:24 +0000 http://html5doctor.com/?p=4628 Guest doctor Mark Boas returns with a follow up to his 2009 article Native Audio in the Browser, which covers the basics of HTML5 audio. Read the original if you want to get a feel for the <audio> element and associated API. If not, get comfortable and dive deep to learn about the current state of play for HTML5 audio.

]]>
This is a follow up to my 2009 article Native Audio in the Browser, which covers the basics of HTML5 audio. It may well be worth reading if you want to get a feel for the <audio> element and associated API.

Now, two and a half years later, it’s time to see how things are progressing. With many new advanced audio APIs being actively worked on and plenty of improvements to the existing native audio we all know and love, it’s certainly an exciting time to revisit the heady world of <audio>.

A good way of understanding how the land lies is by going through a few use cases. That’s what I’ll attempt to do in this post.

So how do we get started? Well, there are a few things we need to do to prepare the ground. Let’s tackle MIME types first.

MIME Types

MIME types (also known as Internet Media Types) are a way of defining file formats so that your system knows how to handle them.

Server Side

First things first: your media server should be configured to serve correct MIME types. In the case of the Apache web server, this means adding the following lines to your .htaccess file:

# AddType TYPE/SUBTYPE EXTENSION
AddType audio/mpeg mp3
AddType audio/mp4 m4a
AddType audio/ogg ogg
AddType audio/ogg oga
AddType audio/webm webma
AddType audio/wav wav

Client Side

When defining sources in your code or markup, you can also specify the MIME type, which will help the browser identify the media correctly.

To set up HTML5 audio in the most robust manner, you could write something like this:

<audio>
   <source src="elvis.mp3" type='audio/mpeg; codecs="mp3"'>
   <source src="elvis.oga" type='audio/ogg; codecs="vorbis"'>
   <!-- add your fallback solution here -->
</audio>

Here we define the element and the sources to use. The browser will only pick one. It won’t play both. In this code, we also place a fallback solution after the <source> elements.

Along with the source, we specify a type attribute. Although not strictly necessary, this attribute allows the browser to know the MIME type and the codecs of the supplied media before it downloads it. If not, supplied the browser will guess and take a trial-and-error approach to detecting the media type.

Cool. So now we know how to define our audio sources, and the browser will happily pick the first source that it supports. But what if we want to supply the correct source in a more dynamic manner?

Knowing in Advance: canPlayType Can Help, Probably

Fortunately the audio API provides us with a way to find out whether a certain format is supported by the browser. But first, here’s a quick recap on how we manipulate the audio element via the API.

If you mark up your element in HTML as we did in our previous example, you can grab the <audio> element by doing the following:

var audio = document.getElementsByTagName('audio')[index];

// or, if you gave it an id attribute
var audio = document.getElementById('my-audio-id');

Alternatively, you can also create your element entirely in JavaScript:

var audio = new Audio();

Once you have your audio element, you’re ready to access its methods and properties. To test format support, you can use the canPlayType method, which takes a MIME type as a parameter:

audio.canPlayType('audio/ogg');

You can even explicitly include the codec:

audio.canPlayType('audio/ogg; codecs="vorbis"');

canPlayType returns one of three values:

  1. probably,
  2. maybe, or
  3. “” (the empty string).

The reason we have these odd return types is because of the general weirdness surrounding codecs. The browser can only guess at whether a certain codec is playable without actually trying to play it.

So to test for support, you could do this:

var audio = new Audio();
  var canPlayOgg = !!audio.canPlayType && audio.canPlayType('audio/ogg; codecs="vorbis"') != "";

All we’re doing here is checking that canPlayType is supported (!! effectively casts to a boolean) and then checking that canPlayType of our chosen format doesn’t return an empty string.

Current Browser Codec Support

Let’s check the codec support in the current crop of modern browsers.

Desktop browser audio codec support
Desktop Browser Version Codec Support
Internet Explorer 9.0+ MP3, AAC
Chrome 6.0+ Ogg Vorbis, MP3, WAV†
Firefox 3.6+ Ogg Vorbis, WAV
Safari 5.0+ MP3, AAC, WAV
Opera 10.0+ Ogg Vorbis, WAV

† WAV since Chrome 9

Mobile browser audio codec support
Mobile Browser Version Codec Support
Opera for Android 14.0+ Device-dependent††
Mobile Safari (iPhone, iPad, iPod Touch) iOS 3.0+ MP3, AAC
Android Stock browser 2.3+ Device-dependent††
Chrome for Android all Device-dependent††
Firefox for Android all Device-dependent††
Firefox OS ? ?
Windows Phone ? MP3, AAC
Blackberry 6.0+ MP3, AAC

†† mobile browsers generally use codecs on the host operating system. Various versions of Android include different codecs. Generally, mp3 and Ogg Vorbis can be assumed. See Supported Media Formats in official Android documentation for more.

The good news is that at the time of writing, it’s estimated that around 80% of browsers now support HTML5 audio.

The bad news is that there is still no consensus on which codec to support, so you’ll need to provide both MP3 and Ogg Vorbis sources in order to take full advantage of HTML5 audio.

Containers, Formats, and File Extensions (oh, and MIME types again)

Above, I’ve referred to the audio formats as they’re commonly known, but technically we should refer to their container format. (A container can contain more than one format — e.g., MP4 can contain AAC or AAC+.)

Container Format(s) File Extensions MIME Type Codec String
MP3 MP3 .mp3 audio/mpeg mp3
MP4 AAC, AAC+ .mp4, .m4a, .aac audio/mp4 mp4a.40.5
OGA/OGG Ogg Vorbis .oga, .ogg audio/ogg vorbis
WAV PCM .wav audio/wav 1

We have <audio> and we’re not afraid to use it!

Okay, we’ve done the minimum amount of work to get our audio element set up and playable. What else can we do? At the moment, we’re relying on the browsers’ default audio players, each of which looks and works a little bit differently than the rest. Perhaps we’d like to customise the experience and create our own. To help us do that, the <audio> element supports several different properties exposing its current state.

Some of the more commonly used properties:

Property Description Return Value
currentTime playhead position double (seconds)
duration media duration double (seconds); read-only
muted is volume muted? boolean
paused is media paused? boolean
volume volume level double (between 0 and 1)

Using these properties is pretty straightforward. For example:

var audio = new Audio();
var duration = audio.duration;

The variable duration now holds the duration (in seconds) of the audio clip.

Buffering, Seeking, and Time Ranges

The situation is improving in this area, as browser makers start to implement key parts of the spec.

The API provides attributes called buffered and seekable that can be used in situations where we want to ascertain which part of the media has been buffered, preloaded, or is ready to be played without delay.

Let’s first take a look at the buffered and seekable attributes. Both return a TimeRanges object. The TimeRanges object is a list of time periods containing start and end times that can be referenced by their indexes.

The buffered Attribute

The buffered attribute will return the time ranges that have been completely downloaded. A little bit of a code:

// returns TimeRanges object of buffered media
var buffered = audio.buffered;

// returns time in seconds of the last buffered TimeRange
var bufferedEnd = audio.buffered.end();

The TimeRanges Object

The TimeRanges object contains data on the parts on buffered media in the form of one or more — you guessed it — time ranges. A TimeRanges object consists of these properties:

  1. length — number of time ranges
  2. start(index) — start time in seconds of a particular time range
  3. end(index) — end time in seconds of a particular time range

You may be wondering in what situation the TimeRanges object would contain more than one time range. Imagine the user clicks forward to a portion of unbuffered media. The idea is that the media would then start buffering from that point, and you’d have two time ranges:

------------------------------------------------------
|=============|                    |===========|     |
------------------------------------------------------
0             5                    15          19    21

So in this case:

  • audio.buffered.length returns 2
  • audio.buffered.start(0) returns 0
  • audio.buffered.end(0) returns 5
  • audio.buffered.start(1) returns 15
  • audio.buffered.end(1) returns 19
  • audio.buffered.end() returns 19

Note that if the user is actively seeking through the media throughout the buffering process, a contiguous buffered progress bar actually makes little sense. Also consider that some browsers will read part of the end of the file to establish duration and so create two time ranges almost immediately. Now you’re starting to appreciate why making an accurate buffered progress bar is a little tricky!

You can check out TimeRanges in real-time using this handy HTML5 Media Event Inspector.

Seeking and Seekable

Seeking is the act of looking forward (or backward) in a media file. This usually happens when a section of media is requested before it’s finished loading.

The seeking attribute can be used to determine whether that part of the media is being actively “seeked”. When it returns true, the portion of the media the user requested is still being loaded.

To recap a little, the buffered property tells us what’s been downloaded and is often used as an indication of what part of the media can be directly played. If the browser supports it, however, it may make more sense to use the seekable attribute to determine which parts of the media can be jumped to and played immediately.

seekable returns a TimeRanges object of time ranges that can be played immediately. This uses a technology known as byte-range requests, which allows part of the content to be requested over HTTP. In short, we don’t have to load all the data prior to the desired part in order to play it.

An example:

// Is the player currently seeking?
var isSeeking = audio.seeking;

// Is the media seekable?
var isSeekable = audio.seekable && audio.seekable.length > 0;

// Time in seconds within which the media is seekable.
var seekableEnd = audio.seekable.end();

Time ranges can be confusing. audio.seekable.end() actually tells us the end point of the last time range (not the end point of all seekable media). In practice, though, this is good enough, as the browser either enables range requests or doesn’t. If it doesn’t, then audio.seekable will be equivalent to audio.buffered, which will give a valid indication of the end of seekable media.

Note that media being in a “seekable” state is different than media being in a “buffered” state. Media doesn’t have to be buffered to be seekable.

Buffered and seekable data can be useful information, but it would be too easy if there weren’t a few gotchas.

  1. Preloading is not supported in all older audio-capable browsers (Opera 10/Firefox 3.6).
  2. The buffered attribute is not always supported (Blackberry PlayBook).
  3. Not all HTML5 browsers allow byte-range seeking — for example, Safari on Windows. In this case, you can still seek within the downloaded content. It downloads from the start until the end, as does Flash.

If you want to deliver the best possible solution to your users, you’ll need to feature test.

A Note about Preloading

I mentioned the preload attribute in the previous article. This attribute accepts three possible values:

  1. none — Do not preload any media. Wait for a play event before downloading anything.
  2. metadata — Preload just the metadata. Grab the start and the end of the file via range-request and determine the duration.
  3. auto — Preload the whole file. Grab the start and the end of the file to determine duration, then seek back to the start again for the preload proper.

When it comes to preloading, remember that it’s a request or hint to tell the browser how you’d like to preload the media. The browser is not under any obligation to fulfill that request. For this reason, certain browsers may handle these requests differently.

Well-Played

It’s worth mentioning the played property in passing. This property tells us which time ranges have been played within the media. For example:

// returns a TimeRanges object
var played = audio.played;

Media Events

Underpinning both the native audio and video APIs is a comprehensive set of events. A full list can be found at the WhatWG version of the spec.

Attaching handlers to media events allows you to easily react to changes in state. For example, it might be useful to update the time info in a custom-built player each time the timeupdate event occurs.

A quick summary of the more commonly used media events:

Event Description
durationchange The duration attribute has been updated.
ended Playback has stopped as the end of the media was reached.
pause The media playback has been paused. Note there is no stop event.
play The media has started playing.
timeupdate The current playback position changed (usually every 250ms).
volumechange The volume changed.

Other useful events:

Event Description
canplay The media can be played but may need to pause while the file is downloaded.
canplaythrough At current download rates, it is estimated that the media can be played from start to finish without pause.
progress The browser is fetching the media data (usually every 250ms).

Again, the HTML5 Media Event Inspector is your friend.

Additionally, you can test browser support by using areweplayingyet.org. It’s worth checking out the code behind the tests to understand the goings-on under the hood.

Streaming

Streaming audio is a common requirement. This is an area that until recently has been dominated by Adobe’s Flash technology. Proprietary server technologies and protocols are well-established. One of the leading examples of this is Adobe’s Real Time Messaging Protocol (RTMP). However, current browsers only support streaming over HTTP, and so something like Flash is required to process RTMP streams.

Currently, audio-enabled browsers only support SHOUTcast and Icecast servers that stream audio over HTTP. SHOUTcast is propriety and allows streaming of MP3 and AAC files only, while Icecast is non-propriety and supports Ogg Vorbis as well as MP3 and AAC.

Stream AAC MP3 Ogg Vorbis Native Support
Icecast Yes Yes Yes Yes
SHOUTCast Yes Yes No Yes
RTMP Yes Yes No No (requires Flash)

An Evolving Spec (Or, “Whoa, this thing is moving!”)

As the audio spec is still evolving, there are a couple of inconsistencies in browser implementations to watch out for. These generally affect older browsers.

The load Method

Until fairly recently, the load method was required in order to tell the browser about a change in the media source and to get it to update appropriately. Now, media.load() causes the element to reset and to start selecting and loading a new media resource from scratch.

So for older browsers, such as Firefox 3.6, in order to change the media source, you’ll not only need to change the source value but also issue a load command:

var audio = new Audio();
audio.setAttribute("src","mynew.mp3");
audio.load(); // required for 'older' browsers

When Browsers Go Off-Spec

When creating cross-browser solutions, it’s useful to know which browsers follow the W3C spec to what extent and how they deviate.

Autoplay and Volume

iOS and Blackberry devices ignore the autoplay attribute and media element volume changes, whereas Android supports autoplay but not volume changes.

Effectively, on Blackberry and iOS devices, autoplay functionality is disabled as both require a user-initiated event to “kick it off”. This has the unfortunate side-effect that any audio suffers a delay between user interaction and playback.

To mitigate against these issues, you may want to take a look at Doctor Remy Sharp’s excellent article on Audio Sprites and fixes for iOS.

Simultaneous Playback of Multiple Audio Elements

A particular annoyance for developers of anything but the most simple audio web apps: not all browsers will play multiple audio elements simultaneously. This is a particular problem for games developers. Again, we see this issue with iOS and Blackberry devices.

Operating System Dependence

Safari (5+) relies on Quicktime being installed. This is rarely a problem unless you are running it on Windows.

Internet Explorer (9+) relies on the codecs being present at the operating system level. As it only runs on Windows, this is fortunately almost always the case.

What’s New?

There are a few new features and whole new APIs being specified for web-based audio, so let’s take a look at what’s around the corner.

A Change of Pace

A couple of noteworthy upcoming features are playbackRate and defaultPlaybackRate. As you can probably imagine, these fellas let us alter the speed and direction of playback. This functionality could be used for fast-forward and rewind functions or perhaps to allow users to tweak the playback speed so they can fit more podcasts into their day.

  • audio.playbackRate returns 1 at normal speed and acts as a multiple that is applied to the rate of playback. For example, setting playbackRate to 2 would double the speed, while setting it to -1 would play the media backwards.
  • audio.defaultPlaybackRate is the rate at which the audio will play after you pause and restart the media (or issue any event for that matter).

Media Fragments

Currently, if we wish to reference some part of a media file, we often first have to download at least some of the media we don’t actually need. The W3C Media Fragments proposal was created to address this issue and others, such as the retrieval of an area of video or just the associated text track. In the case of audio, it will allow us to specify which parts we want to download using parameters on the source URI.

Advanced Audio APIs: The Future Sound of Browsers

When it comes to more advanced audio functionality, Mozilla was first to enter the fray with an early experimental Audio Data API for Firefox. This was intended to facilitate audio manipulation via JavaScript and created a platform for low-level tinkering.

Not to be outdone, Google released the Web Audio API for Chrome and put it forward as a W3C proposal. The Web Audio API is a higher-level implementation that takes an audio-node based approach and provides many useful functions.

Both implementations address the desire by developers to do more with audio — to create, manipulate, analyse, and mix audio on the fly. In effect, we may one day be able to do in a browser anything we can currently do with native applications.

So what if we want to play with advanced audio in the browser? Well, two separate implementations currently exist. If you want to write applications that use both APIs in any reasonable way, you need third-party bridging libraries to abstract away the differences.

Also fairly new on the scene is Mozilla’s MediaStream Processing API, which takes another approach to audio and video streams to allow us to manipulate at both high and low levels.

In fact, using advanced APIs and taking advantage of the speed of modern JavaScript engines, we can even write decoders for unsupported codecs. Currently, we have the JSMad MP3 decoder and the lossless Alac.js decoder. Apparently, FLAC and AAC are in the pipeline. There is hope, then, that in the future, we may not have to worry about which browsers are supporting which formats.

For those curious about advanced web audio, I wrote about the differences in approaches and the different libraries that allow us to write cross-browser solutions in HTML5 Audio APIs: How Low can we Go?

The good news is that all relevant parties are talking, and things seem to be buzzing on the W3C Audio Working Group. It looks like everyone is coming together to put their ideas into a unified Audio Processing API, which is rapidly approaching publication as a Web Standard.

Summary

Although browser implementations of the current HTML5 audio spec are improving, there are still a few issues to watch out for when creating comprehensive cross-browser solutions. You certainly need to be aware of browser limitations on platforms like iOS. Hopefully, as support matures, these issues will disappear.

Positive news on the “advanced audio” front too: a new standard is being established, and we’re close to get a unified spec for browser makers to work from. In the meantime, JavaScript libraries are available to help bridge the gaps between existing implementations.

There are also signs that we may be seeing the end of the requirement for different browser-dependent codecs. Opera Mobile already supports MP3 where the underlying OS supports it, and Mozilla look like they may enable this too. If this option exists for mobile browsers, it’s not a huge stretch to imagine that desktop browsers will follow suit.

So lots happening and lots already achieved. The rough edges of existing browser implementations are being smoothed, consensus and standards are being forged, and we can see the foundations of some very exciting new technologies being established.

The future of web-based audio looks bright!

HTML5 Audio — The State of Play originally appeared on HTML5 Doctor on May 8, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/html5-audio-the-state-of-play/feed/ 32
Drag and Drop and Automatically Send to the Server https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/ https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/#comments Tue, 03 Apr 2012 13:30:17 +0000 http://html5doctor.com/?p=4500 I realised (when looking myself) that there are a lot of demos and tutorials that show you how to drag-and-drop a file into the browser and then render it on the page. They're often labelled as "drag-and-drop and upload", but they actually don't upload. This tutorial will take you that final step.

]]>
I realised (when looking myself) that there are a lot of demos and tutorials that show you how to drag-and-drop a file into the browser and then render it on the page. They're often labelled as "drag-and-drop and upload", but they actually don't upload. This tutorial will take you that final step.

I'll walk you through an example that you can play with: drag a file into the web page, and it'll be uploaded to the server instantly.

Tasks

Let's break this process down into specific tasks:

  1. Capture the drop event and read its data.
  2. Post that binary data to the server.
  3. Provide feedback on the progress of the upload.
  4. Optionally render a preview of what's being uploaded and its status.

To achieve all of this, we need the following HTML5 and non-HTML5 APIs:

  1. Drag and Drop
  2. FormData
  3. XHR progress event
  4. FileReader

Keep in mind that not all browsers support all of this technology today, but they're getting close. I just wanted to create a clear and complete tutorial on how to go the whole hog and upload that dropped file.

The end result: we're able to drop the file anywhere in the browser, we get a preview and progress of the upload, and it's a slick experience.

Drag and drop upload
Our drag-and-drop example page

Drag and Drop

Just as a forewarning, drag-and-drop has been known to be a bit of a killjoy. In fact, it's a nightmare, but I won't repeat what's been said before.

Our example is going to allow you to drag-and-drop a file anywhere within the browser. To achieve that, we need to attach our event listeners to the body or documentElement (i.e., the root HTML node). By listening on the documentElement, this code could be anywhere in the page, as documentElement will always exist. You can only listen on body once the <body> element has been encountered.

Here's the pattern of code we need to capture the drop event on the entire document:

var doc = document.documentElement;
doc.ondragover = function () { this.className = 'hover'; return false; };
doc.ondragend = function () { this.className = ''; return false; };
doc.ondrop = function (event) {
  event.preventDefault && event.preventDefault();
  this.className = '';

  // now do something with:
  var files = event.dataTransfer.files;

  return false;
};
Basic pattern for capturing drop events

I'm using the hover class so that I can toggle a tip explaining to the user that the file can be dropped on the page.

Inside the drop event, we can access the dropped files via event.dataTransfer.files.

An Alternative to Drag and Drop

Annoyingly, as I write this, I realise this combination of API requirements is currently only met by Chrome and Firefox. So, taking the test from Modernizr, we can test for support and provide our alternative:

var dndSupported = function () {
  var div = document.createElement('div');
  return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
};

if (!dndSupported()) {
  // take alternative route
}
Testing for drag-and-drop support

Instead of drag-and-drop, we can insert a file input element (I've given it an id of "upload"), and when its value is changed, the file can be scooped in:

document.getElementById('upload').onchange = function (event) {
  // `this` refers to the element the event fired upon
  var files = this.files;
};
An alternative to native drag-and-drop

You can see the equivalent is simply the files property of the HTMLInputElement object. This will give us access to the same file as the event.dataTransfer.files from the drop event.

Automatically Uploading the File

This is the neat bit, and it's painfully simple. We use a feature of the XHR2 spec: FormData. Once we create an instance of FormData, we can append items to it:

var formData = new FormData();
for (var i = 0; i < files.length; i++) {
  formData.append('file', files[i]);
}

// now post a new XHR request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
xhr.onload = function () {
  if (xhr.status === 200) {
    console.log('all done: ' + xhr.status);
  } else {
    console.log('Something went terribly wrong...');
  }
};

xhr.send(formData);
Creating and posting FormData

Yeah, that's it.†

Let's look at a couple of key things that are going on the above code.

formData.append('file', files[i]);

We're sending named parameters to our server, specifically an array of values called file. Obviously, you can call it what you want, but the file is the name your server will be looking for when it saves the uploaded file (or files).

xhr.onload = function () {
  if (xhr.status === 200) {
    console.log('all done: ' + xhr.status);
  } else {
    console.log('Something went terribly wrong...');
  }
};

If you're familiar with XHR, you'll notice we aren't listening to onreadystatechange, only onload — which is (in effect) a convenience function to let you know when the readyState is 4 (i.e., loaded!). You should still check and respond appropriately to the status code of the request to ensure it's 200 OK, rather than a 500 (internal server error) or 404 (not found) or anything else.

xhr.send(formData);

The nice trick here is that XHR has automatically set the encoding of the posted data to multipart/form-data. This encoding allows your server to read and save the files. It's like the encoding used when you send an attachment in an email.

Providing Feedback to the User

XHR2 now (flippin' finally) comes with a progress event. So if you're sending or retrieving a large file via XHR, you can tell the user how far along you are.

It's pretty simple. If you want to track the progress of the XHR request, listen to the progress event. One gotcha that caught me out for some time: I needed to track the progress of the upload, not the download. To do this properly, you need to listen for progress on the XHR upload object, as so:

xhr.upload.onprogress = function (event) {
  if (event.lengthComputable) {
    var complete = (event.loaded / event.total * 100 | 0);
    progress.value = progress.innerHTML = complete;
  }
};

xhr.onload = function () {
  // just in case we get stuck around 99%
  progress.value = progress.innerHTML = 100;
};
Providing feedback with XHR2's progress event

Note that instead of xhr.onprogress, we use xhr.upload.onprogess. When this event fires, we check that the event supports calculating the amount of data uploaded (the lengthComputable part), and then calculate the amount completed.

In my HTML, I'm using a <progress> element (similar to the <meter> element, but more semantically appropriate as we're presenting the progress of a task) to show the user how much of their file has been uploaded:

<progress id="progress" min="0" max="100" value="0">0</progress>

Note that I'm using innerHTML for browsers that don't yet support <progress>. Then with a dash of CSS-generated content, both the innerHTML and value of the progress can be the same (perhaps an over optimisation, but I was rather proud of myself at the time!).

And Finally, Rendering a Preview

As a nice addition, we'll give the user a preview of what we're uploading for them. It requires the File API — specifically the FileReader API.

As the drag-and-drop operation (or the input[type=file]) contains a file object, we can hand this over to the FileReader to get the contents of the file. If it's something like an image, we can get the Base64 data and give the user a preview. Or if it's text, we could render it in a <div>. The MIME type for the file is available as the type property on the file object.

So let's assume we only accept images. Here's the preview part that runs after the file has been received by the browser:

var acceptedTypes = {
  'image/png': true,
  'image/jpeg': true,
  'image/gif': true
};

if (acceptedTypes[file.type] === true) {
  var reader = new FileReader();
  reader.onload = function (event) {
    var image = new Image();
    image.src = event.target.result;
    image.width = 100; // a fake resize
    document.body.appendChild(image);
  };

  reader.readAsDataURL(file);
}
Rendering a preview of an uploaded image

We create the FileReader and give it a file to read. In the above example, I've used readAsDataURL, but you can also read files in plain text and binary formats (as per the spec).

When the reader has read the file and the data is available, it fires the load event, which in turn creates our new image.

The result of the file read action is in the event.target.result property. In the case of the readAsDataURL, the value is along the lines of data:image/png;base64,ABC....

Using All the Tools in the Shed

This example may be a little contrived for the article that I wanted to write. I've used many different technologies to do something that's a fairly common pattern on the web. In fact, it was because I had trouble finding a definitive source on uploading to the actual server (except, of course, as I wrote this article I found this example from back in late 2010!).

Hopefully, you'll see how each bit of tech can work together to create an application, but equally I hope that you can see where this would work if none or just some of the technology wasn't available. Make sure you detect functionality. Make sure you provide fallbacks. Make sure you develop responsibly.

Here's the final drag-and-drop and upload demo for you to play with.

Drag and Drop and Automatically Send to the Server originally appeared on HTML5 Doctor on April 3, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/feed/ 41
It's Curtains for Marital Strife Thanks to getUserMedia https://stevefaulkner.github.io/html5doctored/getusermedia/ https://stevefaulkner.github.io/html5doctored/getusermedia/#comments Tue, 07 Feb 2012 14:56:03 +0000 http://html5doctor.com/?p=4335 HTML5 (or now, the WebRTC spec) gives us getUserMedia, a way for JavaScript to access streams from a device's camera and microphone. Find out how to use it and normalise the syntax differences between Opera and Chrome with the gUMshield.

]]>
True story: I was tasked by the lovely Mrs Lawson to buy some curtains that match our carpet during the January sales. I dutifully did so — and had to return to the shop straight away because they didn’t match at all. Mrs Lawson accompanied me, and with a withering glance at her incompetent mate, immediately found some correctly hued fabric, and all was well.

But what’s a middle-aged colour-blind bloke to do? I had early in the curtain procurement process decided against cutting a hole in the carpet in order that I may take a sample with me. (All other mistakes aside, this was a correct decision.)

So, in order to ensure that I would never again repeat the mistake, I set out to make an app that would allow me to capture the colour of an image straight from my camera. Of course, it had to be a web app rather than a native app, because we’re web angels, not proprietary devils.

getUserMedia

getUserMedia is an API that gives a web page access to a user’s camera and microphone via JavaScript. It’s supported in Opera 12 and Opera Mobile 12 for Android, and WebKit in Chrome Canary builds (instructions).

Like many other APIs, it’s not part of the “real” HTML5 spec. It started life as the HTML5 <device> element, then got moved into the W3C as part of the webRTC specifications. But let’s not taxonomise when we could be having fun.

The first thing we need to do when using super-cool new UIs is detect whether it’s supported:

 if (navigator.getUserMedia) {
  // do something cool
} else {
  // fallback code
}
Basic usage of getUserMedia

For this article, our “do something cool” will be to grab the dominant colour of the current input stream from the camera. As a fallback, we have several options.

One option, if we’re using the default Android browser, is to show a form that automatically starts the camera when focussed:

<form enctype="multipart/form-data" method="post">
  <input type="file" accept="video/*;capture=camera" />
</form>
Fallback code for Android

There’s also the capture attribute, a proposed extension from the W3C Device API Media Capture API that tells a user agent where to get the input data. Android extends the accept attribute. See more in David Calhoun’s Device API article. Alternative capture arguments are camcorder (for video), microphone, and filesystem.

Browsers that don’t understand the still-draft Media Capture API will simply ignore the capture attrbute and prompt the user to browse to a file on their file system for uploading.

Users on iOS are out of luck, as their devices don’t allow access to the file system.

Differences Between the Media Capture API and getUserMedia

Robin Berjon, co-chair of the Device API (DAP) Working Group explains: The markup-only Media Capture API is a simpler, low-hanging-fruit version that can work easily for a lot of use cases. It also has a very simple security model (just a file upload).

In fact, it works exactly like <input type=file>, except that it knows to allow the user to grab a pic from the camera by default instead of hitting the filesystem. But just like with <input type=file>, once a picture has been taken (i.e., a file selected), you can access it and read from it using the File API, which means you can stuff it in an <img> or a <canvas> and do nasty things to it without annoying any faraway server.

But of course, if it’s part of a form and you submit it, it gets submitted just like a regular file upload.

The thing is, though, it’s always a snapshot. Even if you use it to take a video (which you can), the page only gets it after you’ve finished shooting. With getUserMedia (gUM), you get the live stream, which you can modify, record, or stream elsewhere. The gUM approach is more powerful but more complex, and it has more severe security issues.

getUserMedia API

Let’s assume (because we’re optimists) that your user has a getUserMedia-enabled device. The API is nice and simple, as all Web APIs should be.

navigator.getUserMedia accepts two required arguments and an optional third.

The first argument tells the device which media you require access to, and it’s passed as a JavaScript object. So, if you only require access to the microphone, the first argument would be {audio: true}; for video-chatting, you would use {audio: true, video: true}.

The device decides which camera to use: User agents are encouraged to default to using the user’s primary or system default camera and/or microphone (as appropriate) to generate the media stream.

A previous version of the specification allowed hints to user agents about which camera to use. The API could specify “user” (the front camera on a phone) or “environment” (the rear camera on a phone). Debate continues about whether to reinstate this (read the ongoing conversation). One argument against is that letting sites know what cameras a device has could help Dr Malice of Evil Corp. fingerprint users after luring them to his site (which I find to be overly-cautious). Harald Alvestrand poses a conundrum: conferencing units may have a room camera, a document camera and a lectern camera, neither of which is attached to the physical box; which one of these is front?

But let’s not worry at the moment. Devices with more than one camera generally have a mechanism that allow the user to choose which one is used, so this gives the user control. Note also that the spec says User agents may allow users to use any media source, including pre-recorded media files.

The second argument is the success callback, the function to be executed on success, assuming that the user allows access and the device supports your request.

There is an optional third argument. This is the failure callback, the function to be executed if something went wrong. It’s optional, but only optional in the sense that washing your hands before you eat is optional: if you don’t do it, you leave yourself open to all sorts of bugs and your mum will shout at you.

Of course, it’s important to do feature detection before making an API call to ensure that the browser and device are capable, but even if feature detection succeeds, there is still much that can cause failure. For example, the user could deny permission or turn off the camera via a hardware switch, or the device itself could disable the camera.

So here’s how we recommend you use the API:

navigator.getUserMedia({audio: true, video: true}, success, error);

function success(stream) { 
  // ... use 'stream' ... 
} 

function error(){ 
  // display fallback content 
}
Using the gUM API

To check whether it’s working correctly, we can attach the output of the camera’s stream to the input of an HTML5 video on the page, like this:

<video autoplay></video>
<script>
if (navigator.getUserMedia) {
  navigator.getUserMedia({audio: true, video: true}, success, error);
  function success(stream)
  { 
    // ... use 'stream' ...
    var video = document.getElementsByTagName('video')[];
    video.src = stream; 
  }
  // ...
</script>
Streaming captured video to an HTML5 <video> element

Differences Between Webkit and Opera

The two rendering engines that implement getUserMedia do so in two different ways. Hopefully, they’ll harmonise when the features reach the released browsers.

The differences:

  • WebKit uses a prefix — navigator.webkitGetUserMedia — while Opera doesn’t.
  • WebKit implements the options according to an old version of the spec, in which audio and video were passed as strings:
    navigator.webkitGetUserMedia("video, audio", /* ... */)
    whereas Opera implements the most recent version of the specification which uses JavaScript objects:
    navigator.getUserMedia({video: true, audio: true}, /* ... */)
    (Added June 2012: Chrome 20+ uses the ({video: true, audio: true} syntax.)
  • WebKit attaches the resulting stream like this:
    video.src = window.webkitURL.createObjectURL(stream);
    which is according to the current version of the spec. Opera uses:
    video.src = stream;
    and has proposed simplifying the spec (but discussion continues).

But this fragmentation, even though it’s only in experimental browser releases is, like, a total drag, man.

Introducing The gUM Shield

Fortunately, we’ve got your back. Two of the finest minds I know — actually, two of the finest Mikes, Doctor Mike Robinson and Opera’s Mike Taylor — have created a snippet of script that you can copy to shield you from these annoying differences. We’ve named this getUserMedia syntax normalisation script snippet The gUM Shield.

It assumes that there’s a variable called video to which you’ve assigned a reference to the <video> element you’ll stream to. Do this with some mechanism like:

video = document.getElementById('video');

Simply hit the ‘Hub, download it, plug it into your script, and check it out!

Note that it’s experimental. Who knows what’ll happen when Mozilla, Microsoft, and Apple implement it, but please, have a play. Fork it and improve it!

Doing Exciting Things with the Video Stream

So far, we’re only echoing the video stream. But, as you’ll know from Tab Atkins’ guest article video + canvas = magic, if we copy the video into a canvas, we can manipulate it:

var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

ctx.drawImage(video, 0, 0, video.width, video.height,
  0, 0, canvas.width, canvas.height);
Canvas and video magic

A common mistake is assuming that this somehow establishes a “live connection” between the video stream and the canvas. It doesn’t. It only grabs the current frame. So you need to grab the current frame repeatedly in order to replicate a video. The magical number is 15 times a second (or every 67 milliseconds), but a slower frame rate would probably be okay for this demo:

setInterval(function () { 
  ctx.drawImage(video, 0, 0, video.width, video.height,
  0, 0, canvas.width, canvas.height);
},  67);
Live updating of <canvas> from a <video>

See the working demo.

What I want to do now is to grab the dominant colour from the canvas. I’m stealing a demo by Shwetank Dixit (who borrowed from Lokesh Dhakar‘s Color Thief demo). We won’t look at how it determines the dominant colour (because that’s nothing to do with getUserMedia).

Try this in Opera Labs and Chrome Canary!

Unfortunately, this works splendidly in Opera but it occasionally fails in Chrome, and we’re not sure why. (We’ve emailed the Chrome team to ask them.) Apart from the rather anti-climactic end to an article, you shouldn’t be dismayed by this. getUserMedia is only available in experimental builds that have plenty of work to be done before they hit production.

Back to our demo. Once you’ve got the dominant colour, you could prompt the user for a name for that colour (“carpet”, for example) and store that in local storage using its name as a key. Then, when you find a pair of curtains in the shop, you can find their dominant colour and easily compare it with that stored against “carpet” from earlier.

And you can return home, confident of delighting the love of your life with your chromatically appropriate choice of soft furnishings. That’s HTML5: enriching marriages since 2004.

woman says 'hey daddy-o, the curtains really razz my berries, ya dig?'. Man replies 'Baby, I totally dig. Early night?'. A thought bubble shows him thinking 'Thank you, getUserMedia'

Harshing Your Mellow

Things need refining before web apps with getUserMedia are on a par with native applications. At the moment, there is no way of controlling which camera is to be used (and no agreement that a developer should be able to). The camera’s flash mechanism isn’t programmatically controllable, which could harm the user experience. Most importantly are the privacy implications of web pages being able to access your camera. Opera has an experimental privacy UI, but Chrome has no UI yet.

More Demos

See Paul Neave’s HTML5 Webcam Toy and the links at the foot of my Opera Labs article.

Thanks

Thank for help and code are due to Robin Berjon, Shwetank Dixit, Daniel Davis, Lokesh Dhakar, Mike Taylor, Mike Robinson, and .

Addy Osmani’s Polyfill

Added 13 March 2012: Addy Osmani has published a getUserMedia polyfill called getUserMedia.js, which uses Flash if gUM isn’t available. It’s not ready for production yet, as IE is still being tested. Forkers may hit the ‘hub.

It's Curtains for Marital Strife Thanks to getUserMedia originally appeared on HTML5 Doctor on February 7, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/getusermedia/feed/ 28
Server-Sent Events https://stevefaulkner.github.io/html5doctored/server-sent-events/ https://stevefaulkner.github.io/html5doctored/server-sent-events/#comments Tue, 24 Jan 2012 14:30:33 +0000 http://html5doctor.com/?p=4181

Related Posts:

]]>
We’ve already had a glimpse at Server-Sent Events (also known as EventSource†, and I’ll switch between the two to keep you on your toes) in my Methods of Communication article from last year. In this article, I want to delve in to more detail about the SSE API, demonstrate its features, and even show you how to polyfill browsers that lack EventSource support.

Server-Sent Events are real-time events emitted by the server and received by the browser. They’re similar to WebSockets in that they happen in real time, but they’re very much a one-way communication method from the server.

These events are similar to ordinary JavaScript events that occur in the browser — like click events — except we can control the name of the event and the data associated with it.

All the code for this article is available on github, and a live demo is available online.

† Is it Server-Sent Events or EventSource? Well, they both work. Server-Sent Events is the name of the API and specification. EventSource is the name of the JavaScript object you’re instantiating. It’s a bit like Ajax and XHR, where XHR refers to the XMLHttpRequest object…kinda.

Two notes: a) the uptime for this example is, I’m afraid, usually rather low — good for my server, bad for you. If you test the demo locally it will give you more interesting figures. b) IE6 isn’t supported in any of this article.

Possible Applications

A few simple examples of applications that could make use of Server-Sent Events:

  • A real-time chart of streaming stock prices
  • Real-time news coverage of an important event (posting links, tweets, and images)
  • A live Twitter wall fed by Twitter’s streaming API
  • A monitor for server statistics like uptime, health, and running processes

We’ll use the server monitor for this article’s examples. If this application were to be used in the wild, we could also check the EventSource‘s connection state to indicate when there’s a potential problem connecting to the server.

Overview of the API

The client-side API is rather simple, and it hands-down beats the insane hacks required to get real-time events to the browser back in the bad old days.

The main points of interest:

  • new EventSource(url) — this creates our EventSource object, which immediately starts listening for events on the given URL.
  • readyState — as with XHR, we have a readyState for the EventSource that tells us if we’re connecting (0), open (1), or closed (2).
  • onopen, onmessage — two events that we can listen for on the new EventSource object. By default, the message event will fire when new messages are received, unless the server explicitly sets the event type.
  • addEventListener — not only can we listen for the default message event, but we can also listen for custom messages using the addEventListener on the EventSource object, just as if we were listening for a click event.
  • event.data — as with most messaging APIs, the contents of the message reside in the data property of the event object. This is a string, so if we want to pass around an object, we need to encode and decode it with JSON.
  • close — closes the connection from the client side.

In the future, EventSource will also support CORS using an options argument to the EventSource object: { withCredentials: true }. But at the time of writing, no stable release includes this property.

Simple Example

Our simple web app will notify us of server status messages — things like the load average, number of currently connected users, and most CPU-intensive processes. If I were using this application in anger, I’d probably build server modules that emit specific event types when they cross specific thresholds, so that I’m only notified when something gets to warning level.

This snippet of JavaScript connects to our server, listens for messages, and handles the data that comes with the messages:

var source = new EventSource('/stats');
source.onopen = function () {
  connectionOpen(true);
};

source.onerror = function () {
  connectionOpen(false);
};

source.addEventListener('connections', updateConnections, false);
source.addEventListener('requests', updateRequests, false);
source.addEventListener('uptime', updateUptime, false);

source.onmessage = function (event) {
  // a message without a type was fired
};

Properties of Server-Sent Events

Server-Sent Events are more than just a one-way web socket. They have some unique features:

  • The connection stream is from the server and read-only. This suits lots of applications, some examples of which I listed above.
  • They use regular HTTP requests for the persistent connection, not a special protocol, which means we can polyfill using vanilla JavaScript.
  • If the connection drops, the EventSource fires an error event and automatically tries to reconnect. The server can also control the timeout before the client tries to reconnect.
  • Clients can send a unique ID with messages. When a client tries to reconnect after a dropped connection, it will send the last known ID. Then the server can see that the client missed n messages and send the backlog of missed messages on reconnect.

Message Format

A simple message doesn’t require much:

data: this is a simple message
<blank line>

Note that the end of a message is indicated by a blank line (obviously not the literal characters <blank line>).

For a message with multiple lines:

data: this is line one
data: and this is line two

You can send message IDs to be used if the connection is dropped:

id: 33
data: this is line one
data: this is line two

You can even send multiple messages in a single response so long as you separate the messages by blank lines:

id: 34
data: Remy is awesome

id: 35
data: Bruce is stinky

And you can specify your own event types (the above messages will all trigger the message event):

id: 36
event: price
data: 103.34

id: 37
event: news
data: Bruce sells his collection of replica bananas

You don’t have to worry about this structure on the client side. It only applies to the server, which I’ll touch on next.

Typical Server

I’m not going to give a full walkthrough of the server-side code, since this is an HTML5 web site :) But there are a few important and simple features that you need to know to build the server (you’ll need this part anyway if you’re going to use EventSource).

I’ve included all the files for this demo on GitHub for you to peruse at your own leisure, and I’ve also deployed a live example of this code.

Ideally, you should use a server that has an event loop. This means you should not use Apache, but instead use a platform such as Node.js (which I’ve used) or Twisted for Python.

Key properties:

  1. You can only accept EventSource requests if the HTTP request says it can accept the event-stream MIME type.
  2. You need to maintain a list of all the connected users in order to emit new events.
  3. You should listen for dropped connections and remove them from the list of connected users.
  4. You should optionally maintain a history of messages so that reconnecting clients can catch up on missed messages.

Here’s a sample of my Node.js based server. It’s using Connect (a simple webby framework for Node). When it receives a request for /stats, it calls the following function. I’ve commented the code so you can follow along:

function stats(request, response) {
  // only response to an event-stream if the request 
  // actually accepts an event-stream
  if (request.headers.accept == 'text/event-stream') {

    // send the header to tell the client that we're going
    // to be streaming content down the connection
    response.writeHead(200, {
      'content-type': 'text/event-stream',
      'cache-control': 'no-cache',
      'connection': 'keep-alive'
    });

    // support the polyfill - we'll come on to this later
    if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
      response.xhr = null;
    }

    // if there was a lastEventId sent in the header, send
    // the history of messages we've already stored up
    if (request.headers['last-event-id']) {
      var id = parseInt(request.headers['last-event-id']);
      for (var i = 0; i < history.length; i++) {
        if (history[i].id >= id) {
          sendSSE(response, history[i].id, history[i].event, history[i].message);
        }
      }
    } else {
      // if the client didn't send a lastEventId, it's the
      // first time they've come to our service, so send an
      // initial empty message with no id - this will reset
      // their id counter too.
      response.write('id\n\n');
    }

    // cache their connection - the response is where we write
    // to send messages
    connections.push(response);

    // send a broadcast message to all connected clients with
    // the total number of connections we have.
    broadcast('connections', connections.length);

    // if the connection closes to the client, remove them
    // from the connections array.
    request.on('close', function () {
      removeConnection(response);
    });
  } else {
    // if the client doesn't accept event-stream mime type,
    // send them the regular index.html page - you could do
    // anything here, including sending the client an error.
    response.writeHead(302, { location: "/index.html" });
    response.end();
  }
}

The important trick on the server is to ensure you don’t close the connection to the EventSource object. If you do, it will of course handle the closed connection, fire an error event, and try to reconnect. So you’ll just want to maintain the persistent connection.

Polyfills and Tweaks to the Server

There are two good polyfills I know of, and though I prefer the one I wrote, I’ll still lay them both out for you.

Yaffle’s Polyfill

The first is one by Yaffle (on github), available on github/Yaffle/eventsource.

The cons:

  • It doesn’t send the accepts header, and
  • It completely replaces the EventSource object, so even if your browser supports EventSource natively, this script will replace it. But there’s a good reason for that.

The pros:

  • It maintains a persistent connection (whereas the one we’re using doesn’t), and
  • More interestingly, it supports CORS (which I imagine is why it replaces the native EventSource).

These two pros are quite compelling. But when I was testing, I couldn’t get it working in IE7 (which was my minimum browser target), so that might be a blocker for you…or not.

Remy’s Polyfill

The second is my own, available on github.com/remy/polyfills.

The cons:

  • It uses polling, so once a small group of messages come down, it re-establishes the connection, which could lead to significant overhead (though less so on a Node-based server). You have to add about 4 extra lines to your server code.

The pros:

  • It doesn’t replace the native EventSource object (but that also implies that, for now, it won’t support CORS), and
  • It supports IE7.

Retrospectively, I might choose Yaffle’s polyfill over mine in the future if I wasn’t bothered about IE7 support.

Using the Polyfill

By including the EventSource.js JavaScript library before my client-side code, I just need a couple of small changes to my server-side code. Other than that, everything on the client side works without any changes (as a polyfill should work).

When posting the server’s reply to the client, instead of keeping the connection open, I include the following in my server when it’s finished writing the response:

// send the data (event type, id, message, etc)
response.write(data);

// if our response contains our custom xhr property, then...
if (response.hasOwnProperty('xhr')) {
  // clear any previous timers using the xhr prop as the value
  clearTimeout(response.xhr);

  // now set a timer for 1/4 second (abritrary number) that
  // then closes the connection and removes itself from the
  // connection array.
  // The delay is in place so that a burst of messages can 
  // go out on the same connection *before* it's closed.
  response.xhr = setTimeout(function () {
    response.end();
    removeConnection(response);
  }, 250);
}

Bugs?

The error event should always fire when the readyState changes, assuming you didn’t explicitly call the close method. This works nearly all the time, but in writing this article, I found a few edge cases where it doesn’t fire. In Chrome, if I put my machine to sleep and then woke it back up, it would close the connection but not fire the event, therefore never triggering a reconnection. As I said, this is an edge case and I’ll file a bug against it, so I don’t expect it to hang around for long.

Why Not Use WebSockets?

There are two reasons I’d advocate using EventSource over WebSockets, as they’re currently the two contenders for sending real-time events to the browser.

The first is that EventSource (as we saw earlier) works over regular HTTP and can therefore be replicated entirely using JavaScript if it’s not available natively. That means that we can polyfill browsers without support, like IE9.

The second is probably more important: you should always use the right technology for the job. If your real-time data is sourced from your web site, and the user doesn’t interact in real-time, it’s likely you need Server-Sent Events.

I recently saw a cool demo of snowflakes drifting down a web site. Each snowflake is a tweet based around the Christmas theme — like if someone mentions a particular Christmas-y term, it’s sucked in to the snowflake. Don’t get me wrong, I know this is a demo, and it’s very cool (if you wrote it, this is me sending you hugs), but it’s based on WebSockets. I’d suggest this demo should be based on EventSource since all the data is read-only and the user doesn’t interact with it at all.

The point: evaluate the technology against your problem, and aim to get good fit.

Server-Sent Events originally appeared on HTML5 Doctor on January 24, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/server-sent-events/feed/ 53
Pushing and Popping with the History API https://stevefaulkner.github.io/html5doctored/history-api/ https://stevefaulkner.github.io/html5doctored/history-api/#comments Tue, 15 Nov 2011 13:09:47 +0000 http://html5doctor.com/?p=3897

Related Posts:

]]>
Until recently, we developers couldn’t to do much with the state and history of the browser. We could check the number of items in the history and push users forwards and backwards, but this provides little benefit to the user. With the rise of more dynamic web pages, we need more control. Thankfully, HTML5 gives us that control by extending the JavaScript History API.

What’s the point?

It goes without saying that URLs are important. They’re the method of accessing the vast collections of information and resources on the web, and more recently, they’ve begun representing the intended state of a web application. You can copy these URLs and share them with your friends or use them to create links from any HTML document. They’re the veins of the web, and they need to be looked after.

Previously, the JavaScript History API offered some very simple functionality:

// Check the length of the history stack
console.log(history.length);

// Send the user agent forward
console.log(history.forward());

// Send the user agent back
console.log(history.back());

// Send the user agent back (negative) or forward (positive)
// by a given number of items
console.log(history.go(-3));

With dynamic Ajax web applications, where the browser updates the page in parts instead of changing location entirely, it’s difficult to give the user a URL to bookmark or share the current application state. Fragment identifiers, like those used on this article’s headings via the id attribute, provide some state information, but they’re entirely dependent on client-side scripts.

The changes to the History API are intended to give developers ways to push history items to the browser so the native back and forward actions can cycle through those items. These history items can also hold data that you can later extract to restore the page state.

Pages can add state objects between their entry in the session history and the next (“forward”) entry. These are then returned to the script when the user (or script) goes back in the history, thus enabling authors to use the “navigation” metaphor even in one-page applications.

If the user copies or bookmarks a stateful URL and visits it later, your back-end can be configured to interpret such a URL and jump the user right to the correct page and/or state.

In this article, I’ll cover the client-side use of the History API, so make sure you set up your server to work with the new URLs. If you’ve already built an accessible website that provide these entry points, you’re laughing!

Those f#!king hashbangs…

You may have already seen articles fussing over the adoption of the “hashbang” (#!) pattern on sites like Twitter. This technique updates the address bar with a fragment identifier that can then be used by JavaScript to determine which page and state should be displayed.

This works as a method of creating a bookmarkable, shareable URL for a page’s state in the absense of a standard API. While the Twitter implementation accepts both http://twitter.com/#!/akamike and http://twitter.com/akamike, it has some disadvantages:

  • The fragment identifier is only accessible on the client side. This means that only JavaScript can utilise it, so browsers without JavaScript enabled are out of luck.
  • As the server does not receive the path following the hashbang, removing that JavaScript drops support for all those URLs. That’s a lot of broken links, so you’re stuck with that JavaScript forever.
  • It’s ugly. It’s a hack and it looks like one.

The hashbang was never intended to be a long-term solution, so don’t rely on it. If you do use hashbangs, be prepared to deal with the consequences (and possible backlash from web purists).

Making History

These examples will build on top of each other. We’ll start with a basic HTML document with some inline styles and scripts for your convenience.

Save this file and open it in your favourite editor. It must be accessed via HTTP, so that means you need either a local server (e.g. http://localhost/) or an online web server you can upload to. Viewing the file directly using your browser’s Open File function will not work, since it uses the file:// protocol and not HTTP. Also be sure to update the href attributes on each of the navigation links to ensure the correct directory structure is used. Personally, I’m viewing the demo locally at http://localhost/history.

We’ll be working exclusively within the <script> element at the end of the <body>. The code includes some simple styles and dynamically changes the content as you click the links. In reality, this could be loaded from your server via XMLHttpRequest, but for the purposes of this demonstration I’ve bundled it up into a self-contained file. The important part is that we have a quick-and-dirty dynamic page to work with, so let the fun begin!

At the moment there, is no bookmarkable URL for the different states of this page. If you click around the navigation items, then click Back in your browser, you won’t be taken back to the previous state and may even be taken away from the page to whatever you viewed before (depending on your browser). It would be nice if you could share “Socks” with your friends, right? We can do that via history.pushState().

The history.pushState() method takes three parameters:

data
Some structured data, such as settings or content, assigned to the history item.
title
The name of the item in the history drop-down shown by the browser’s back and forward buttons. (Note: this is not currently supported by any major browsers.)
url (optional)
The URL to this state that should be displayed in the address bar.

With these parameters, you can define the state of the page, give that state a name, and even provide a bookmarkable address, as if the page had reloaded entirely. Let’s dive right in and add this to the clickHandler function, right above the return statement:

function clickHandler(e) {
  /* Snip... */

  // Add an item to the history log
  history.pushState(data, event.target.textContent, event.target.href);

  return event.preventDefault();
}

The single line of code we added informs the history object that:

  • we want to add an item to the log,
  • it should remember the data that we’ve already loaded,
  • it should assign a name to this state based on the text of the link we clicked (even though this isn’t used — it’s good to get into the habit of recording a name for the state), and
  • it should update the address bar with the href attribute of that link.

Reload the page in your browser and click a few of the links, keeping an eye on the address bar. Notice how it changes on each click, despite the fact that you aren’t actually navigating away from this page. If you also have a look at your history log, you’ll see a long list of page titles (in this case ”Kittens!” over and over). Provided your server is set up to serve the correct page upon access, the user could copy that URL and paste it into a new browser window to jump straight to that kitten.

At the moment, clicking the back button will pop you through the history items, but the page won’t react to these changes. That’s because so far, we’ve only created the history records. How can we allow active users to return to a previous state? We listen to the popstate event.

Historical Events in Navigation

The user agent fires a popstate event when the user navigates through their history, whether backwards or forwards, provided it isn’t taking the user away from the current page. That is, all those pushStates we called will keep the user on the current page, so the popstate event will fire for each history item they pop through.

Before the closing </script> tag, add a new listener for the popstate event:

// Revert to a previously saved state
window.addEventListener('popstate', function(event) {
  console.log('popstate fired!');

  updateContent(event.state);
});

We attach the event listener to the window, which is responsible for firing the event, and pass this event into our handler. We log a message (so we can see when this event is firing), and then we update the content using the state we saved previously. The state is attached to the event object via the state property.

Open up the page fresh in your browser, click around like before, and then click back. As before, the URL in the address bar changes as you cycle through states, but now the content is also restored back to what it should be. Click forward, and the content is likewise correctly restored.

If you look at the developer console in Chrome when you load the page for the first time, you’ll see the popstate event fired immediately, before you’ve even clicked a link. This is because Chrome considers the initial page load to be a change in state, and so it fires the event. In this instance, the state property is null, but thankfully the updateContent function deals with this. Keep this in mind when developing as it could catch you out, especially if other browsers assume this behavior.

Rewriting history

Unfortunately, as fantastic as HTML5 is, it doesn’t allow us actual time travel. If it did, I would be going back to my childhood and telling a younger me, “Yes, you should have a slice of cake”. Take that as you will.

The History API does, however, allow us to make amends to our history log items. For example, we could update the current state in response to fresh user input in a form. We can do this with history.replaceState.

replaceState works just as pushState does, with the exact same parameters, except that it updates the current entry instead of adding a new one. I can think of one situation in our demo where this could be used: the initial page load. If you click back for long enough, you’ll find that going back to the original URL doesn’t provide you the original content. Let’s fix that by adding the following to the bottom of our script:

// Store the initial content so we can revisit it later
history.replaceState({
  content: contentEl.textContent,
  photo: photoEl.src
}, document.title, document.location.href);

As this runs when the page loads, it saves the initial page state. We can later load this state when the user browses back to this point via the event listener we set up previously. You can try it out by loading up the page, clicking a few links, and then hitting back until you return to the original URL. The initial content has returned!

Demo

I’ve set up a demo of our completed code. I’ve also added a little back-end magic to make our history.pushState URLs work like a real site. Remember that the URLs you push should be live URLs that the user can bookmark and share as real entry points to your site.

View the History API demo

Browser support

Up-to-date copies of Chrome (5+), Safari (5.0+), Firefox (4.0+), and Opera (11.50+) have support for the new History API. Even some mobile browsers work just fine, like Mobile Safari on iOS 4+. Unfortunately, IE 9 and below lack support, but it when it arrives.

Safari 5.0 sometimes exhibits one oddity: navigating between states causes the loading spinner to appear and stay even when the state has been loaded. This stops when you navigate away using a link or action that does not involve a state saved by the History API.

Polyfill

A polyfill does exist for the History API. The aptly named History.js uses HTML4’s hashchange event with document fragment identifiers to mimic the history API in older browsers. If one of the hash URLs is used by a modern browser, it uses replaceState to quietly correct the URL.

It sounds like magic, but make sure you’re aware of the consequences of using fragment identifiers, as mentioned previously in this article. As such, the author of History.js has put together a guide titled Intelligent State Handling.

Closing thoughts

URLs go beyond just the browsing session of a user. They’re historically important markers for resources that could very well remain in use for many years to come. Before you embark on developing your site’s JavaScript, you should give thought to the design of your URLs. Make them meaningful and organised. Make sure you can directly access them without JavaScript. Only then should you add your JavaScript to enhance the browsing experience.

Pushing and Popping with the History API originally appeared on HTML5 Doctor on November 15, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/history-api/feed/ 26
Storing Data the Simple HTML5 Way (and a few tricks you might not have known) https://stevefaulkner.github.io/html5doctored/storing-data-the-simple-html5-way-and-a-few-tricks-you-might-not-have-known/ https://stevefaulkner.github.io/html5doctored/storing-data-the-simple-html5-way-and-a-few-tricks-you-might-not-have-known/#comments Tue, 23 Aug 2011 14:00:36 +0000 http://html5doctor.com/?p=3600

Related Posts:

]]>
Yes indeed people, it’s your favourite HTML5 Doctor with JavaScript knowledge who lives in Brighton near a golf course! I’m also shooting for the longest title we’ve published so far – and I think I’m in the lead.

This post is about the Web Storage API. Technically it’s been shifted out of the HTML5 specification and can now be found in it’s very own dedicated spec. But if it counts at all – it used to be part of the Web Applications spec.

Web Storage is a very, very simple way to store data in the client – i.e. the browser. What’s more, the support is fabulous: IE8 and upwards has support natively, and there’s lots of good polyfills in the wild already.

This post however will just focus on the features of Web Storage and hopefully show you a trick or two you may not have known about.

What Web Storage Does

Using JavaScript, Web Storage makes it possible to easily store arbitrary values in the browser. Storage is different from cookies in that it’s not shared with the server. It’s also different from cookies in that it’s dead simple to work with.

There are two versions of Web Storage: local and session. Local means that it’s persistent, and session is simply that the data is lost when the session ends (i.e. when you close you browser window or tab). It’s also worth noting that a session is tied to a single browser window or tab. The session doesn’t leak out in to other open windows on that same domain.

Any data stored is tied to the document origin, in that it’s tied to the specific protocol (http or https, etc), the host (html5doctor.com) and the port (usually port 80).

Get Storing

The API for localStorage and sessionStorage is exactly the same, and distills down to the following methods:

  • .setItem(key, value);
  • .getItem(key)
  • .removeItem(key)
  • .clear()
  • .key(index)
  • .length

You can probably guess what most of those methods do, maybe not the last two, but ignore all that syntax for a moment.

Due to the way that the storage API has been defined, the set/get/remove methods all are getters, setters and deleters. What that means to you is you can use localStorage as follows:

localStorage.name = 'Remy';

If you tried using the link above, this will save a property called “name” against localStorage. Completely closing your browser, and going back to http://jsconsole.com and test the name property again:

console.log(localStorage.name);

Still holds the value doesn’t it? Pretty easy eh? And no faffing around with cookies, for that, we can be thankful!

Equally deleting data is very easy:

delete localStorage.name;
console.log(localStorage.name);

You’ll see the value is undefined.

What’s happening under the hood is that when you set a property on localStorage (or sessionStorage) it’s calling the .setItem method. When you get a property, it’s calling .getItem and when you delete, it’s calling removeItem. That way you can treat the Web Storage interface as any other regular object in JavaScript, except you’ll know it’ll hang around after the page has unloaded.

Hey everyone! I’m storing some data!

That’s what your browser does when you store some data. It announces it via events.

When you set some data on localStorage or sessionStorage, an event, called “storage”, fires on all the other windows on the same origin.

To listen for events the following code is used:

function storageEvent(event) {
  event = event || window.event; // give IE8 some love
  alert('Yo people! Something just got stored!');
}

if (window.attachEvent) { // ::sigh:: IE8 support
   window.attachEvent('onstorage', storageEvent);
} else {
    window.addEventListener('storage', storageEvent, false);
}

Note that as IE8 has support, if you don’t want to use onstorage you’ll want to double up your event listeners with attachEvent.

Clearly a massive alert box isn’t useful, but what is useful is what you capture inside of the event object:

  • key – the property name of the value stored
  • newValue – the newly set value (duh!)
  • oldValue – the previous value before being overwritten by .newValue
  • url – the full url path of the origin of the storage event
  • storageArea – the storage object, either localStorage or sessionStorage

With this information, you can do a lot with the storage event, like perhaps keep tabs that are open synchronised. Here’s a simple, contrived example of using localStorage to echo a value across different windows on html5demos.com.

Or for a real world example, Font Deck recently implemented this very feature, if you change the sample text in one window, all other open tabs (or windows) mirror that same sample text.

Gotchas to watch out for

The main gotcha with Web Storage is that although the specification used to say† that any object type can be stored, in fact all browsers currently coerce to strings. That means if you want to store a JavaScript object (or an array perhaps), you’ll need to use JSON to encode and decode:

var doctors = [
  'rem', 
  'rich_clark', 
  'brucel', 
  'jackosborne', 
  'leads', 
  'akamike', 
  'boblet'];
localStorage.doctors = JSON.stringify(doctors);

// later that evening…
var html5docs = JSON.parse(localStorage.doctors);
alert('There be ' + html5docs.length + ' doctors in the house');

† Edited thanks to feedback from zcorpan

When working with storage events, a couple of things to also watch out for – this is on purpose of course, but still just about qualify for gotcha status:

  1. The event only fires on the other windows – it won’t fire on the window that did the storing.
  2. The event won’t fire if the data doesn’t change, i.e. if you store .name = ‘Remy’ and set it to ‘Remy’ again it won’t fire the storage event (obviously, since nothing was stored).

and finally…

If you want to use web storage in browsers like IE6 and IE7 (or rather than want: need to in your particular case) – then there’s no shortage of polyfills for Web Storage. However be wary that you’ll need to stick to the regular setItem syntax rather than being able to use the sexy setter/getter syntax – and I’ve yet to see a polyfill that supports the storage events.

Maybe that isn’t a problem for you though – maybe the sheer simplicity and spiffingness of Web Storage is enough to just support IE8 and above with this enhanced client storage model.

Storing Data the Simple HTML5 Way (and a few tricks you might not have known) originally appeared on HTML5 Doctor on August 23, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/storing-data-the-simple-html5-way-and-a-few-tricks-you-might-not-have-known/feed/ 32
Finding your position with Geolocation https://stevefaulkner.github.io/html5doctored/finding-your-position-with-geolocation/ https://stevefaulkner.github.io/html5doctored/finding-your-position-with-geolocation/#comments Tue, 14 Jun 2011 14:35:07 +0000 http://html5doctor.com/?p=3324 The Geolocation API provides a method to locate the user's exact (more or less - see below) position. This is useful in a number of ways ranging from providing a user with location specific information to providing route navigation.

]]>
The Geolocation API provides a method to locate the user’s exact (more or less – see below) position. This is useful in a number of ways ranging from providing a user with location specific information to providing route navigation.

Although it’s not actually part of the HTML5 specification, as it was developed as a separate specification by the W3C, rather than the WHATWG, if the esteemed HTML5 Doctors Remy Sharp and Bruce Lawson felt it was fitting enough to include in their book, then it’s perfectly ok to write about it here.

The API is actually remarkably simple to use and this article aims to introduce the API and show just how easy it is.

Browser Compatibility

Currently the W3C Geolocation API is supported by the following desktop browsers:

  • Firefox 3.5+
  • Chrome 5.0+
  • Safari 5.0+
  • Opera 10.60+
  • Internet Explorer 9.0+

There is also support for the W3C Geolocation API on mobile devices:

  • Android 2.0+
  • iPhone 3.0+
  • Opera Mobile 10.1+
  • Symbian (S60 3rd & 5th generation)
  • Blackberry OS 6
  • Maemo

Data Protection

The specification explicitly states that since the nature of the API also exposes the user’s location and therefore could compromise their privacy, the user’s permission to attempt to obtain the geolocation information must be sought before proceeding. The browser will take care of this, and a message will either appear as a popup box, or at the top of the browser (implementation is browser specific) requesting the user’s permission.

Screenshot of Safari's popup box asking for Geolocation permission
Safari asking the user for permission to obtain their Geolocation information

Geolocation sources

A number of different sources are used to attempt to obtain the user’s location, and each has their own varying degree of accuracy. A desktop browser is likely to use WiFi (accurate to 20m) or IP Geolocation which is only accurate to the city level and can provide false positives. Mobile devices tend to use triangulation techniques such as GPS (accurate to 10m and only works outside), WiFi and GSM/CDMA cell IDs (accurate to 1000m).

Using the API

Before you actually attempt to use the Geolocation API, you first need to check if the browser actually supports it. The API usefully provides a function for this which can be called as follows:

if (navigator.geolocation) {
  // do fancy stuff
}

Obviously if this returns false, you should optionally inform the user of the inferiority of their browser and laugh in their face (not really).

Through the API, there are two functions available to obtain a user’s location:

getCurrentPosition and watchPosition

Both of these methods return immediately, and then asynchronously attempt to obtain the current location. They take the same number of arguments, two of which are optional:

  1. successCallback – called if the method returns successfully
  2. [errorCallback] – called if the method returns with an error
  3. [options] – a number of options are available:
    • enableHighAccuracy – provides a hint that the application would like the best possible results. This may cause a slower response time and in the case of a mobile device, greater power consumption as it may use GPS. Boolean with a default setting of false.
    • timeout – indicates the maximum length of time to wait for a response. In milliseconds with a default of 0 – infinite.
    • maximumAge – denotes the maximum age of a cached position that the application will be willing to accept. In milliseconds, with a default value of 0, which means that an attempt must be made to obtain a new position object immediately.

Before mentioning the differences between the two, another method needs to be introduced:

clearWatch

This method takes one argument, the watchID of the watch process to clear (which is returned by watchPosition)

Now, the main difference between getCurrentPosition and watchPosition is that watchPosition keeps informing your code should the position change, so basically it keeps updating the user’s position. This is very useful if they’re on the move and you want to keep track of their position, whereas getCurrentPosition is a once off. This method also returns a watchID which is required when you want to stop the position constantly being updated by calling clearWatch method is called.

When the user’s position is returned, it is contained within a Position object which contains a number of properties:

Property Details
coords.latitude Decimal degrees of the latitude
coords.longitude Decimal degress of the longitude
coords.altitude Height in metres of the position above the reference ellipsoid
coords.accuracy The accuracy in metres of the returned result. The value of this setting informs the application how useful the returned latitude/longitude value actually is. This can help in determining if the returned result is accurate enough for the purpose it is intended for, e.g. values for streetview locations will need to be more accurate than those for a country based location
coords.altitudeAccuracy The accuracy in metres of the returned altitude
coords.heading Direction of travel of the hosting device, clockwise from true north
coords.speed The current ground speed of the hosting device in metres per second
timestamp Timestamp of when the position was acquired

Amongst these only which is coords.latitude, coords.longitude and coords.accuracy are guaranteed to be returned (all others may be null), and the first two are by and large the most relevant, as it is from these that a position can be plotted on a Google Map, for example.

You can read more about the Position object and the coordinates interface on the W3 specification itself.

Putting it all together

Putting this altogether, the following code will attempt to obtain a user’s location, calling the method displayPosition on success which simply pops up an alert box with the captured latitude and longitude:

if (navigator.geolocation) {
  var timeoutVal = 10 * 1000 * 1000;
  navigator.geolocation.getCurrentPosition(
    displayPosition, 
    displayError,
    { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
  );
}
else {
  alert("Geolocation is not supported by this browser");
}

function displayPosition(position) {
  alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}

The code above also calls the displayError method when attempt to fetch the user’s location data. This function simple converts the returned error code to an appropriate message:

function displayError(error) {
  var errors = { 
    1: 'Permission denied',
    2: 'Position unavailable',
    3: 'Request timeout'
  };
  alert("Error: " + errors[error.code]);
}

A final word

This is just a simple introduction to using the Geolocation API and one of it’s uses.

Of course the API can be used for more than simply plotting a position on a map (although that in itself is quite useful). The specification itself offers a list of potential use cases for the API such as:

  • Finding and plotting points of interest in the user’s area
  • Annotating content with location informationShowing a user’s position on a map (helping with directions of course!)
  • Turn-by-turn route navigation – using watchPosition
  • Up-to-date local information – updates as you move

Examples

To see geolocation in action, I’ve put together a couple of quick examples in which I encourage you to view source and then go and try it out for yourself.

Finding your position with Geolocation originally appeared on HTML5 Doctor on June 14, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/finding-your-position-with-geolocation/feed/ 43