What is the difference between localStorage, sessionStorage, session and cookies?

后端 未结 8 1669
抹茶落季
抹茶落季 2020-11-22 03:07

What are the technical pros and cons of localStorage, sessionStorage, session and cookies, and when would I use one over the other?

8条回答
  •  無奈伤痛
    2020-11-22 03:35

    Local storage: It keeps store the user information data without expiration date this data will not be deleted when user closed the browser windows it will be available for day, week, month and year.

    In Local storage can store 5-10mb offline data.

    //Set the value in a local storage object
    localStorage.setItem('name', myName);
    
    //Get the value from storage object
    localStorage.getItem('name');
    
    //Delete the value from local storage object
    localStorage.removeItem(name);//Delete specifice obeject from local storege
    localStorage.clear();//Delete all from local storege
    

    Session Storage: It is same like local storage date except it will delete all windows when browser windows closed by a web user.

    In Session storage can store upto 5 mb data

    //set the value to a object in session storege
    sessionStorage.myNameInSession = "Krishna";
    

    Session: A session is a global variable stored on the server. Each session is assigned a unique id which is used to retrieve stored values.

    Cookies: Cookies are data, stored in small text files as name-value pairs, on your computer. Once a cookie has been set, all page requests that follow return the cookie name and value.

提交回复
热议问题