Blog


JavaScript in Internet Explorer 8

Our day has finally come. CSS coders got some love with Internet Explorer 7 - us JavaScript folk got absolutely nothing. In fact, at last count, all we got were a couple new bugs to deal with (file:// requests not working via XMLHttpRequest and <object>.getElementsByTagName("*") always returning no elements).

Internet Explorer 8 is our release.

The first beta was pushed out today and it shows huge promise. It's already achieved way more than I would've expected and it's made me hungry for more. If you had bet me that Microsoft would be mentioning the phrases "ARIA", "SVG", and "MathML" in their release notes I would've lost.

Here are my thoughts on a bunch of the browser features:

W3C: querySelector

A super-fast way of finding elements based upon a CSS selector. The second browser to implement the selectors API has hit the market (behind a WebKit nightly release).

It's important to realize that any selectors here are completely reliant upon the browser's native selector implementation. IE8 is only shooting for CSS 2.1 support - which means that you really shouldn't be holding your breath for CSS 3 selectors. As I mentioned previously these blackbox APIs are going to be a source of never-ending hair-pulling and struggle going into the future.

HTML 5 Party!

I was hoping for some HTML 5-compliant features to land - well, hoping isn't the right term, perhaps 'feverishly expecting the worst' is more correct. However we can see that we've been graced with 4 full feature implementations from the spec - fantastic!

HTML 5: window.location.hash

Already supported fairly well by most browsers. Modifying window.location.hash changes the page URL and adds the page to the history (allowing for back-button simulation in Ajax applications). IE went a step further and broadcasts the hashchanged event (the first browser to do so, as far as I know).

HTML 5: DOM Storage

A feature that I discussed previously in which data can be persisted in a way that supersedes the use of primitive cookies storage. This has been in Firefox since version 2 but is absent from Opera and Safari.

HTML 5: postMessage

As I discussed previously postMessage serves as a way of communication across frames with simple text strings. IE 8, Opera 9, Firefox 3, and WebKit nightlies all support this feature - making it the only one with complete browser support.

HTML 5: Offline Events

As I've written about previously this is an easy way of detecting connectivity within the confines of JavaScript. With it we can write graceful offline Ajax applications. Firefox 3 and IE 8 appear to be the only browsers to support this feature.

XDomainRequest

This is an interesting feature for doing cross-domain requests but doesn't appear to conform to the existing Cross-site XMLHttpRequest work which is in Firefox 3. Even at that it appears to be quite crude - forfeiting any form of filtering or security controls for a simple boolean "yes/no" header.

Seeing this new API concerns me. The Cross-site XMLHttpRequest work may be in some flux, as some API points are still being hammered down, but it's doubtful that the resolution will end with something identical to what's being described by Microsoft.

DOM bug fix love

getAttribute/setAttribute have seen a major overhaul - in short: They now behave like they should and as they do in every other browser. The notorious issue of accessing relative/absolute href/src attributes is also resolved - which is just great. They also saw fit to add hasAttribute.

Also newly fixed/added:

  • .ownerElement and .ownerDocument - Finally we have a unified way of dealing with iFrames.
  • getElementById returns elements by id - ONLY. Been such a long time coming, thank goodness.
  • Doing getAttribute("checked") now returns "checked" instead of true.
  • <button/> values are actually submitted now, instead of their inner text values.
  • Dynamically created (or modified) radio buttons are now checkable.

I simultaneously feel both joy and anger in seeing these fixed. Happy that they're being released and anger for the fact that I had to struggle through them and that they now consume some portion of my brain.

W3C: Events

This is one area that is completely absent from this beta. We are still stuck with IE's attachEvent system - no addEventListener in sight. I don't know how serious they are about supporting Acid3 but it includes a test for addEventListener so they may want to consider it extra strongly.

I can partially understand their desire to keep their existing API but I don't understand why they have no interest in, also, adding addEventListener, etc. to complement what's there. I assume it's because they would now have to support concepts like event capturing.

I'm really disappointed with this. This should've been a top priority fix before implementing new psuedo-XHR systems like XDomainRequest.

JavaScript Language

The IE team has made some big improvements in improving garbage collection issues, memory management, and performance - all of which will be greatly appreciated in everyday applications.

Although, I mis-spoke slightly earlier: While IE8 is been great for JavaScript developers I was implying "JavaScript + DOM" developers. For pure JavaScript it's completely frustrating: There doesn't appear to be any new pure-JavaScript features in this release. I can only hope that we'll see more in a future beta release.

ARIA Support

This one completely blew me away. ARIA is a fantastic specification for empowering web applications with the ability to clearly communicate their intentions to a screen reader. The biggest hurdle with the effort, up until this point, has been the lack of IE support - obviously this will no longer be the case. Firefox, IE, and Opera all support ARIA now. The WebKit team doesn't appear to have interest in implementing this feature, which is a real shame.

Embedded SVG

Support for embedding namespaced elements within XHTML is now possible. This means that you can now do inline markup for SVG and MathML, amongst others, and have it "just work" (as long as you have their associated plugins installed). It's probably a bit much hoping for native SVG support, but I'll take what I can get.

Firebug for Internet Explorer

We finally have a heavily-Firebug-inspired tool inside Internet Explorer. To quote Joe Hewitt (creator of Firebug): "I couldn't be happier that Microsoft completely copied Firebug for IE8." I have to agree - a tool like this has been a long time coming and it's greatly appreciated. Only the Internet Explorer team would've ever been the ones to build this tool - there's simply too much information here that's unavailable to typical IE extensions.

Browser mode toggling

At first glance this feature makes the most sense for seeing if your IE 7 page will work ok in IE 8. In actuality, however, this will end up being very useful for developing a standards-compliant page (in IE 8, FF, Safari, Opera) and then toggling to see what the result is like in IE 7. This is so much better than the IE 6 to IE 7 jump where you have to keep your browser in a virtual machine in order for it to run side-by-side (according to Microsoft, at least - even though there were standalone solutions).

Bug Feedback

The Internet Explorer team is collecting feedback from select beta testers and publishing the bugs on a publicly-accessible site. This a huge step in the right direction (going from no communication to some is great). "Common" users are forced to vote for their "favorite" bugs to try and catch the eye of an IE developer. It's a strange situation but one that shows progress, at least.

Conclusion

In all I'm positive about this release, even with all the ups-and-downs. Seeing features like querySelector, ARIA, and postMessage helps to warm my frosty, bitter, heart. While there's still some major faux-paus in this release (no new JS langauge features?, no W3C events?, no CSS3 selectors?) I think we can, at least, be excited to see what happens in the next beta.

If nothing else the Internet Explorer team has done a great job of tackling many of the expectations of the development community - if they continue this trend I don't think anyone will be left disappointed.

Tags: ie, browsers, html5, dom, javascript

HTML5 Shiv

Assuming that it'll be a while before most browsers attempt to implement most of HTML 5 (a perfectly reasonable assumption) we need to start thinking of ways to tackle the creation and rendering of HTML 5 components in the meantime. Obviously, using the tools of JavaScript and CSS we can accomplish a lot.

However, there is one notch in our weapon: Internet Explorer doesn't know how to render CSS on elements that it doesn't recognize. For example, the following "blah" element (a fictional element) doesn't have any styling:

<html>
<head>
<style>blah { color: red; }</style>
</head>
<body>
<blah>Hello!</blah>
</body>
</html>

Result:

Thankfully, Sjoerd Visscher mentioned an interesting technique that could be used to force IE to use the specified CSS styling. Specifically, once you create a new DOM element (of the same name as the one in the document) all styling is applied. You don't even have to inject the element in order for this to occur. Observe the following:

<html>
<head>
<style>blah { color: red; }</style>
<script>document.createElement("blah")</script>
</head>
<body>
<blah>Hello!</blah>
</body>
</html>

Result:

This is very important. This now means that we can provide CSS styling for undefined HTML 5 element and allow Internet Explorer to handle it gracefully.

<figure/> element

Let's take a look at a simple example. Pretending that we wanted to set about implementing the HTML 5 figure element. The element is quite simple, only requiring some basic CSS markup (I'm not completely sure how a figure is supposed to look so I took some liberties here).

<html>
<head>
<style>
  figure { border: 1px inset #AAA; padding: 4px; }
</style>
<script>document.createElement("figure");</script>
</head>
<body>
<figure>
  <img src="http://ejohn.org/files/jeresig-wordpress-sm.jpg"/>
</figure>
</body>
</html>

Result:

Using some basic CSS, and a single JavaScript DOM statement, we've now implemented at least part of the HTML 5 spec. While it won't solve everything, it is a promising technique, at the very least.

I did have some issues when I was testing this technique, especially with the styling of elements that are already defined elsewhere in the structure. For example, let's say you wanted to implement the legend child element of a caption. This ends up being really hard since the functionality and styling of legends are already defined for fieldsets by Internet Explorer. In my simple tests they became unstylable outside the context of a fieldset.

This is definitely a decent start, building our HTML 5 shiv, but it needs some more work and much more exploration. I hope to see this continued in the upcoming months as interest in, and availability of, HTML 5 begins to heat up.

Tags: css, javascript, ie, html5

HTML5 DOCTYPE

Remember the whole crazy Internet Explorer 8 meta http-equiv hub-bub, yesterday? There was one post in all of that mess that was really, really, important.

To sum it up: Internet Explorer 8 will support DOCTYPE switching for new DOCTYPEs (like HTML5).

“Steve”: Are there any doctypes that do not require this new meta tag to render with the IE8 rendering engine?

Chris Wilson: @Steve - sure. Any unknown (i.e. not widely deployed) DOCTYPE. HTML5, for example.

This really does change any frustration that someone should have concerning the new meta tag. This means that you can write your web pages in a completely standards-based way (CSS, HTML5, JavaScript) and not have to use a single browser-centric tag in order to do so.

For those of you who aren't familiar with the HTML5 DOCTYPE, it looks like this:

<!DOCTYPE html>

You'll note that it's significantly simpler than most DOCTYPEs that you've seen - and that was intentional. A lot has changed in HTML5 in an attempt to make it even easier to develop a standards-based web page, and it should really pay off in the end.

What's nice about this new DOCTYPE, especially, is that all current browsers (IE, FF, Opera, Safari) will look at it and switch the content into standards mode - even though they don't implement HTML5. This means that you could start writing your web pages using HTML5 today and have them last for a very, very, long time.

If nothing else, this should be a good excuse to look through the changes in HTML5 and familiarize yourself with what's in the pipeline for browsers - Internet Explorer included.

I really, really, wish this was made clear yesterday - it would've avoided a whole lot of pain and suffering on the part of the Microsoft Task Force of WaSP and of the Internet Explorer team as a whole. I'm really glad that this is happening, though - the future of standards-based web development still looks quite bright.

Tags: html5, browsers

Offline Events

Another feature that's coming along, into Firefox 3, from the WHATWG Web Applications 1.0 spec is that of Online/Offline events. This feature serves as the second piece to the "Offline Web Application" puzzle (The first being DOM Storage), that's really coming into place in Firefox 3.

What is the purpose of offline events?

Effectively, in order to build a good offline application, you need to know when you're actually offline. Incidentally, you also need to know when your application has returned to an 'online' status again.

Generally speaking, the flow for an offline-capable web application would look something like this, written completely in pseudo-code:

function saveData( item ){
    if ( navigator.onLine ) {
        saveToServer( item );
    } else {
        toSave.push( item );
    }
}

function loadData( item ){
    if ( navigator.onLine ) {
        return loadFromServer( item );
    } else {
        var result = loadFromQueue( item );
        if ( !result ) {
            displayError();
            toLoad.push( item );
        }
        return result;
    }
}

setInterval(function(){
    if ( navigator.onLine ) {
        var item = predictNextItemToBeLoaded();
        loadData( item );
    }
}, 5000);

window.ononline = function(){
    toSave.forEach( saveData );
    toLoad.forEach( loadData );
};

window.onload = function(){
    document.getElementById("myform").onsubmit = function(){
        saveData( this );
        return false;
    };
};

As you can see from this code, there are two very important aspects at play:

  1. You need to know when the service comes back online, so that you can re-synchronize with the server.
  2. You need to know when your service is offline, so that you can be sure to queue your requests for a later time.

It is this process that offline events helps to trivialize. So let's take at the API that we're given by the specification:

navigator.onLine

This is a single property that maintains a true/false value (true for online, false for offline). Currently, this property is updated (in Firefox) whenever you switch into "Offline Mode" (more details at the end of this post).

Additionally, this property should update whenever a browser is no longer capable of connecting to the network. According to the specification:

The navigator.onLine attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail)...

As of this time, Firefox only appears to update this property when switching to/from the browser's Offline mode.

One point that I found to be curious, about this property, was it's naming. It appears as if someone originally felt that "online" was spelled "on-line" (and since you can't have dashes in JavaScript property names, converted it to its camelcase equivalent, "onLine"). Unsurprisingly, this naming convention is a bit of legacy.

Interestingly, this property already exists in Firefox and Internet Explorer (the specification based itself off of these prior implementations), so you can begin using them today.

"online" and "offline" events

These two events are the truly-new aspects of offline events. They are fired against the document body of any page that switches inbetween online and offline mode. Additionally, the event bubbles up from document.body, to document, ending at window. Both of the events are non-cancellable (you can't prevent the user from coming online, or going offline).

As a side note, Mozilla has had these built in to its XPCOM layer for some time now, specifically the network:offline-status-changed event.

A Simple Test

In the ticket that describes the implementation of these events in Firefox, there's a simple test case that you can run to verify that the events are working.

Considering that you probably don't want to go through the trouble of building your own copy of "Minefield", let's take a quick look at what happens in this test's code.

<!doctype html>
<html>
<head>
  <script>
    function updateOnlineStatus(msg) {
      var status = document.getElementById("status");
      var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
      status.setAttribute("class", condition);
      var state = document.getElementById("state");
      state.innerHTML = condition;
      var log = document.getElementById("log");
      log.appendChild(document.createTextNode("Event: " + msg + "; status=" + condition + "\n"));
    }
    function loaded() {
      updateOnlineStatus("load");
      document.body.addEventListener("offline", function () {
        updateOnlineStatus("offline")
      }, false);
      document.body.addEventListener("online", function () {
        updateOnlineStatus("online")
      }, false);
    }
  </script>
  <style>...</style>
</head>
<body onload="loaded()">
  <div id="status"><p id="state"></p></div>
  <div id="log"></div>
</body>
</html>

There are four important lines to take note of: 7, 16, 19, and 26. We'll be looking at them in depth here.

You'll notice, that if you tried to run the test in your browser (even if you didn't have the bleeding-edge build), that it worked! You probably saw a result just like this:

Why is this the case? As I mentioned before, Firefox already has support for the navigator.onLine event, the only thing that's been added was the addition of events to notify you when the property changes. Incidentally, you can still bind an onload="" event and check for a browser's online/offline status there.

Now, you might be asking yourself (as I did), when can a page load and NOT have a status of "online"? Upon reading through some of the information available, it appears as if this can occur when a page is loaded directly from the browser's cache, while you're in an offline mode. These are the steps that Mark Finkle took to reproduce this:

  • Load a web page from a bookmark.
  • Put the browser into offline mode.
  • Close the browser.
  • Open the browser. (Incidentally, you're back in online mode.)
  • Re-enable offline mode.
  • Click the bookmark again, and you'll be visiting the "offline" copy of that page.

Let's take a look, now, at the browser's "Work offline" mode, and what that offers to us web application developers.

Enable Offline Mode

In a nutshell: Offline mode is a means, through which, a user can tell the browser to be much greedier, and possibly more proactive, about the caching that it performs. Effectively, a browser will try to use the browser's cache as much as possible.

In order to move into offline mode, you can toggle the menu option like so:

This triggers the "offline" event - giving your web application the ability to react, and behave, accordingly.

Disable Offline Mode

Additionally, when it comes time for the user to move back into "online" mode, another event is fired (which can be handled and interpreted).

Summary and Comments

This is a really handy feature, and certainly a great tool for making offline web application simpler. I'm looking forward to its widespread adoption.

My biggest gripe with the feature, right now, is more in its implementation (rather than its concept). There's a huge amount of ambiguity concerning what "Working Offline" means. It's not really clear what is supposed to happen when that menu option is triggered - nor, what exactly, is supposed to trigger the online/offline events.

I see a huge amount of potential in Firefox 3's offline capabilities, however they really need to be clarified - and made useful to the user. Hooking "offline" mode purely to network connectivity would be a great start. (Forcing the user to toggle some sort of offline mode is cumbersome - especially considering that most of the time that I go offline, it's not of my own free will.)

In short: I think Firefox 3 is off to a great start, in supporting offline web applications, but we still have a ways to go in order to make the whole process (both for users and for developers) as smooth as possible.

Tags: browsers, javascript, firefox, mozilla, dom, offline, html5

getElementsByClassName in Firefox 3

I've been waiting for this one for a while - and it was just committed to the Mozilla trunk yesterday:
Firefox 3 is going to have support for getElementsByClassName.

Robert Sayre just merged in his changes yesterday, taking this feature live.

If you're curious as to why this feature is being included (or where the reasoning for it originated from) - it's because it's part of the Web Applications 1.0 (HTML 5) specification. The implementation that's in Firefox is slightly different from what's presented in the specification; however, you can expect that the specification will probably be updated to reflect that changes that've been made.

getElementsByClassName has long been a mainstay of web developers everywhere - and by making it official (both in specification and in implementation), web applications are going to see a huge jump in speed.

I've pulled together some simple examples of what you can do with this new element selector.

Get all elements that have a class of 'test'

document.getElementsByClassName('test')

Get all elements that have a class of 'red' and 'test'

document.getElementsByClassName('red test')

Get all elements that have a class of 'test', inside of an element that has the ID of 'main'

document.getElementById('main').getElementsByClassName('test')

And if we go ahead and add in JavaScript 1.6's Array extras, we can do some really-cool matches.

Find all div elements that have a class of 'test'

Array.filter( document.getElementsByClassName('test'), function(elem){
    return elem.nodeName == 'DIV';
});

Find all elements that have a class of 'test' (as do their parent element)

var test = document.getElementsByClassName('test');
Array.filter( test, function(elem){
    return Array.indexOf( test, elem.parentNode ) > -1;
});

Some basic code can be found in the test cases for this feature. You'll need to have a nightly version of Firefox in order to run the code contained within it. I really can't wait until this is live.

Update: This post has been submitted to Digg.

Update: This function is now documented on the MDC Wiki.

Tags: javascript, traversing, whatwg, dom, getelementsbyclassname, traversal, html5

DOM Storage Answers

In a follow-up to my previous post on DOM Storage, here's an attempt to answer some of the questions posed in the comments, and elsewhere.

What’s to stop a script from filling an entire storage area with random data?

As best as I can tell with the implementation in Firefox, every time you save data to a storage area, not only is the name of the storage area saved (e.g. "org" or "ejohn.org") but so is the domain name of the original script. This domain name is what has the 5MB limitation imposed upon it.

This means that a single script could put 2MB of data in globalStorage['org'] and another 3MB in globalStorage['ejohn.org'], but attempting to put any more data in will cause an error to occur.

I may be wrong on this point; but if that's the case, then it will be very hard to stop scripts from filling up "common" areas with nonsense data (and which seems like something that was considered as a fundamental design decision).

(Update: This is, currently, a moot point in Firefox as it does not enable any of the TLD or public storage areas, for fear of an issue like this happening.)

Storing data to globalStorage['localdomain']

I forgot to mention that all LAN addresses receive a TLD of 'localdomain'. For example, if your computer is named 'anthrax', you could store data in the following stores: globalStorage['anthrax.localdomain'], globalStorage['localdomain'], and globalStorage[''].

This means that you can, in fact, store data "globally" across all pages of an intranet.

What's with the name "DOM Storage"?

I've been having trouble pinpointing this one - but I agree, the name is particularly deceptive. What's especially confusing is that "DOM Storage" isn't the official name for this particular feature, "Client-side session and persistent storage" is.

As it happens, Mozilla's internal name of this features is "DOMStorage" (the names "Storage", "mozStorage", and "sessionStorage" were all already in use), I'm beginning to suspect that this naming confusion has stemmed from this, original, feature-naming. (Note: This has been confirmed.)

In reality, the storage area doesn't really have much to do with the Document Object Model - it really only attaches to the WindowHTML Object. The only time it actually interacts with the DOM, as we know it, is to trigger a "storage" event on the document body.

The storage event

I forgot to mention this in my last post, but this is a rather interesting sub-feature of DOM Storage. Whenever a key/value is changed, added, or removed within a storage area that you have permission to access, a 'storage' event is triggered, originating from the HTML document body and bubbling its way up.

The only piece of event metadata that is passed along in the event object is the name of the domain that the changed-key is within - and nothing else. (Providing any additional information would serve to be a security risk)

Update: Firefox does currently support this, and you can view a test case here.

Server-side Data

No data from DOM Storage areas is automatically passed to the server. This differs from cookies, which serve as a two-way form of synchronous communication between a server and a browser.

You could work around this limitation with an XMLHttpRequest, POSTing the contents of your relevant storage areas.

Known Bugs

As I mentioned before, Firefox has the only known implementation of DOM Storage available to any browser. However, there are still some serious limitations with it.

  • sessionStorage - Does not restore data across browser crash/restore.
  • globalStorage['org'] - Storing data to a single TLD fails
  • globalStorage[''] - Storing data to a public area fails

Update: Neil Deakin has gotten back to me and mentioned that the lack of TLD or public storage areas was intentional. When implementing the specification he felt that there was, quite simply, too much of a security risk in leaving those public areas open. I suspect that since Firefox is the first browser to make an attempt an implementation, much of this will trickle back to the specification.

We're still in the rocky first moments of this feature, but once it starts to pick up some solid adoption (especially amongst other browsers), I suspect that we'll see the level of quality really start to take off.

Tags: domstorage, whatwg, javascript, html5, firefox, mozilla

DOM Storage

The first thing that I tasked myself with, when I hopped on board with Mozilla, was to learn everything that I could about the new DOM Storage functionality provided in the HTML 5 specification. Interestingly, it's actually very impressive.

The brief summary: DOM Storage is a way to store meaningful amounts of client-side data in a persistent and secure manner.

I've written up a thorough piece of documentation on DOM Storage, and it can be found on the DevMo Wiki.

If you hadn't guessed already, DOM Storage is most similar, in nature, to HTTP Cookies. I'm going to already assume that you know how Cookies work, so with that in mind, here is how DOM Storage compares.

Storage Space

It is implied that, with DOM Storage, you have considerably more storage space than the typical user agent limitations imposed upon Cookies. However, the amount that is provided is not defined in the specification, nor is it meaningfully broadcast by the user agent.

If you look at the Mozilla source code we can see that 5120KB is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 2KB cookie.

However, the size of this storage area can be customized by the user (so a 5MB storage area is not guaranteed, nor is it implied) and the user agent (Opera, for example, may only provide 3MB - but only time will tell.)

Storage / Retrieval

Where as in cookies you have to encode your key/value pairs into a string, along with other information (such as expiration and path), DOM Storage is a breath of fresh air. It provide a clean, JavaScript-like API for accessing and mutating key/value pairs. For example:

// Save a value
sessionStorage[ 'name' ] = "John";
// Display a value
alert( sessionStorage[ 'name' ] );
=> 'John'

This is absolutely fantastic, in comparison to Cookies. Note that, like with cookies, you can only store strings of data as a value. Additionally, no form of object serialization is provided by the browser, making some storage tasks non-trivial.

At this point, I'd be happy with one of two solutions: 1) For the user agent to take care of object (de)serialization for us, making it completely seamless or 2) To provide us with a really good, really fast, JSON (de)serializer. Honestly, I'd prefer the second solution, simply because it could be used in so many other situations. (And if I've heard right, one is definitely in the works by multiple browser vendors.)

Security

Cookies provide you with the ability to limit the accessibility of your key/value pairs to a certain domain, and even a certain path within that domain. DOM Storage works similarly, but only allows you to restrict access to domain (or TLD, or even public!) or session.

The data stored in a DOM Storage area is much more "public" than what's provided by cookies. For example, let's say you wanted to use DOM Storage on a public site like LiveJournal. There would be no way for you to hide your data from other users -- other than to choose a key that is completely private and un-reproducible; since there is no "path" limiter for DOM Storage.

Additionally, unlike in cookies, where you're immediately provided with all available key/value pairs for your particular domain (and path), in DOM Storage you must request a key by its specific name (you can't iterate through all available keys).

In short: If you are only using DOM Storage within a single domain (and you control that domain), then you have nothing to worry about - your data is very safe. In any other context you must choose a secure key name that cannot be duplicated by other clients on other sites (unless, of course, that's your goal).

Scope

DOM Storage provides you with a greater variety of scope for a piece of data, than for that of Cookies. For example, if I wanted to store a piece of data on this domain I could store it with the sessionStorage, globalStorage['ejohn.org'], globalStorage['org'], or globalStorage[''] DOM Storage areas. Here is how the restrictions break down:

  • sessionStorage is limited to the current browser session, only. No other client can access this data.
  • globalStorage['ejohn.org'] All pages on my web site have access to this area.
  • globalStorage['org'] All web sites with the TLD of 'org' can access this area (including, for example, mozilla.org).
  • globalStorage[''] All pages on all sites can access this area.

I, personally, think that we're going to see the most interesting results come from sessionStorage and globalStorage['']. sessionStorage for its practicality (which I'll discuss in a minute) and globalStorage[''] for its potential deviousness.

Duration

In DOM Storage it is not possible to specify an expiration period for any of your data. All expiration rules are left up to the user. In the case of Mozilla, most of those rules are inherited from the Cookie-related expiration rules. Because of this you can probably expect most of your DOM Storage data to last at least for a meaningful amount of time.

The one storage area that is particularly interesting (and where expiration does not apply) is that of sessionStorage. sessionStorage is seemingly useless at first blush - it only stores data within the context of a single session. However, there are two, very important, qualifiers to that:

  1. Data is persistent across page refreshes. This is nice because you can now help to protect against accidental page refreshes, by temporarily caching a user's unsaved data.
  2. Data is persistent across browser crashes. This is up to the user agent, but in the case of Firefox if you browser crashes, and you restore your previous session, then your sessionStorage area will be restored. (Well, that'll be the case once Firefox actually implements this feature).

This isn't to say that either of these features aren't possible using cookies, but the similar solution wouldn't be nearly as elegant.

Summary

In all, I'm really looking forward to digging in to DOM Storage - I think it has a lot of potential. Currently, the state of affairs is pretty slim (Firefox is the only browser that has an implementation, and even then, sessionStorage isn't terribly useful yet.) - but the future is bright.

As I mentioned before, if you're interested in some basic examples and documentation on the subject, feel free to read through the DOM Storage documentation that I wrote.

Update: Here's the original bug report that detailed its implementation in Gecko.

Tags: mozilla, domstorage, html5, whatwg, dom, javascript, firefox

· « Previous entries

Current Projects

jQuery JavaScript Library

jQuery

Comprehensive DOM, Event, Animation, and Ajax JavaScript Library.

Recent Projects

Pro JavaScript Techniques

JavaScript Book

The best techniques for professional JavaScript. Published by Apress.