Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Storing Objects in HTML5 localStorage

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 653
    Comment on it

    In HTML5 there is a new feature of localStorage. With this feature web pages store data locally inside the user’s web browser.
    Earlier, cookies were used for storing data. The data is used only when it is asked. also you can not store large data as there will be a limit. The data is stored in the form of name and value pair.
    There are different types that you can store like strings, numbers, objects, complex objects arrays etc.

    To check If local storage is supported in your browser, you need to write this code:
     

    if(typeof(Storage)!=="undefined")
      {
      // Code for localStorage/sessionStorage.
      }
    else
      {
      // Sorry! No Web Storage support..
      }

    The Get & Set methods:

    Strings:
     

    var name = your name!!;
    localStorage.setItem(name,name);
    // get string
    console.log(localStorage.getItem(name)); // will return your name!!

    Numbers:
     

    var count = 12;
    localStorage.setItem(count,count);
    // get string
    console.log(localStorage.getItem(count)); // will return 12 as string
    // parsing to int
    var count = parseInt(localStorage.getItem(count)); // 12
    //or
    var count = parseFloat(localStorage.getItem(count)); // 12

    Objects:
     

    var info = {name:yourname',age:12,gender:male};
    localStorage.setItem("userinfo,info);
    //fetch object
    console.log(localStorage.getItem("userinfo)); // will return "[object Object]"

    when you write the above code for storing a object, it will not give the real object instead it will return the string “[object Object]”. That will be saved in the Local storage. You can write the below code that will return the stringifyed object:

    var info = {name:yourname',age:12,gender:male};
    localStorage.setItem("userinfo,JSON.stringify(info));
    //fetch object
    console.log(localStorage.getItem("userinfo)); // will return {name:yourname',age:12,gender:male}

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: