Skip to main content

How To Append Data to HTML5 localStorage or sessionStorage?

The localStorage property allows you to access a local Storage object. localStorage is similar to sessionStorage. The only difference is that, while data stored in localStorage has no expiration time untill unless user deletes his cache, data stored in sessionStorage gets cleared when the originating window or tab get closed.

These are new HTML5 objects and provide these methods to deal with it:


The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem().

localStorage.setItem('myFav', 'Taylor Swift');
or you can use the keyname directly as :
localStorage.myFav = 'Taylor Swift';

To grab the value set in localStorage or sessionStorage, we can use


localStorage.getItem("myFav");
or
localStorage.myFav


There's no append function for localStorage or sessionStorage objects. It's not hard to write one though.The simplest solution goes here:


But we can keep things modular and separate this as a function so to managed easily as below:


Note: It makes more sense to define a function append on the localStorage object. However, because localStorage has a setter, this is not possible. If you were trying to define a function using localStorage.append = ..., the localStorage object will interpret this attempt as "Save an object called append in the Storage object".

If you are still confused about When to use localStorage v/s sessionStorage, here is a small comparision:

Storage Type Max Size Persistence Availability to other Windows/tabs Data Type Supported
LocalStorage 5MB per app per browser. According to the HTML5 spec, this limit can be increased by the user when needed; however, only a few browsers support this On disk until deleted by user (delete cache) or by the app Shared across every window and tab of one browser running same web app String only, as key-value pairs
SessionStorage Limited only by system memory Survives only as long as its originating window or tab Accessible only within the window or tab that created it String only, as key-value pairs

Comments

Popular posts from this blog