1.

What is the use of localStorage in Html5?

Answer»

HTML5 introduced different approaches for web developers to save persistent content on a user’s machine namely Local Storage, aka Web Storage and WebSQL Storage. Local Storage feature is easy and here is the syntax for storing and retrieving.

<script> localStorage.setItem(“Name”, “Sreekanth”); var firstName = localStorage.getItem(“Name”); </script>

Information is stored as key-value pair and can be easily stored and retrieved using a simple API. Event handlers can also be registered to monitor for changes to localStorage values.  localStorage is well supported in modern browsers and it is consistently supported across desktop and mobile browsers.

The localStorage OBJECT provides much more space than was available with older tools. Modern browsers support a minimum of 5 MB of data, which is substantially more than is allowed through cookies (which are LIMITED to 4 KB each).

If the storage limit is reached, or if the user manually turns off storage capabilities, QuotaExceededError exception is thrown. Below code is to be used to prevent an exception to the user.

try { localStorage.setItem('firstName', $('#firstName').val()); } catch(e) { // degrade gracefully }

Currently, only string values can be stored in web storage, but SOMETIMES we might need to store arrays or JavaScript objects. To accomplish this,  we need to use JavaScript Object Notation (JSON) UTILITY methods.

The following example creates a JSON object and uses the stringify() method to convert the value to a string that can then be PLACED in web storage and use the parse() method to deserialize a new instance of the object from the string representation of the object that was stored

var person = { firstName: sreekanth', lastName: boya' }; localStorage.setItem(‘person', JSON.stringify(person));   var person = JSON.parse(localStorage.getItem(‘person '));

localStorage is designed to retain data across multiple sessions.



Discussion

No Comment Found