HTML5 session storage send to server

Grégory picture Grégory · May 28, 2013 · Viewed 12.8k times · Source

If I'm right, Session Storage is stored client side and is accessible only for one tab.

How can I send information stored in the session storage to the server ? I can use cookie for that, but if I open 2 tabs, the cookie will be rewrite by the second tab.

Thanks

Answer

user1693593 picture user1693593 · May 28, 2013

The Storage object (both localStorage and sessionStorage) is available from all tabs having the same page open.

However (some comment state this is not correct, but this is a misinterpretation of the documentation), when you open a new tab a new storage object is created internally. This is a clone of the first one so the content at that point is the same.

They are treated separate from that point, but you synchronize them by listening to the storage event in your code.

From http://dev.w3.org/html5/webstorage/#the-sessionstorage-attribute: (note that the specs are addressing the implementers)

When a new top-level browsing context is created by cloning an existing browsing context, the new browsing context must start with the same session storage areas as the original, but the two sets must from that point on be considered separate, not affecting each other in any way. [...] When the setItem(), removeItem(), and clear() methods are called on a Storage object x that is associated with a session storage area [...], then for every Document object whose Window object's sessionStorage attribute's Storage object is associated with the same storage area, other than x, send a storage notification.

That is to say that when a storage is modified in the active tab, a storage event is sent to all the other tabs (for the same origin) - but not the active tab which of course isn't needed as this is the one being modified.

Use the event to read the key and newValue fields to update the localSession in the currently inactive tab(s) (there is also the oldValue on the event). The storageArea contains the Storage object that is affected (useful if you use both local and session storage).

As to "one domain" - yes, the same data will only be available to the same origin (scheme, domain and port).

Sending the data to server is fully possible. Everything stored in Storage (session and local) is stored as a string. I would recommend encoding it though (JSON is not necessary as it is already stored as a string). Use f.ex:

var dataForServer = encodeURIComponent(sessionStorage.getItem(myKey));

Then send it as part of a form, url or by ajax.