How to save some values permanently on a browser?

后端 未结 2 1661
走了就别回头了
走了就别回头了 2021-01-28 04:11

I have some login information, let say user name, login email Id and location.

I want keep this information in the browser even after the user logout an

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-28 05:03

    LocalStorage is considered to be the best solution for storing values permanently in the browser.!! A good explanation about the LocalStorage can be found here.

    This is my code used to save the value to the LocalStorage.

             function saveLoginNameToLocalStorage()  
                    {
                     if(typeof(Storage)!=="undefined")//checks whether the browser support localStorage
                      {
                            // you dont want to create a variable by var variablename, 
                            // just give it as localStorage.yourVariableName, before assigning 
                            // any values the variable is shown as  undefined.
                             if(localStorage.userName && localStorage.userName !="" && localStorage.userName==document.getElementById("userName").value){
                                document.getElementById("redirectUrl").value=localStorage.redirectURI;
                            }
                            else{
                                localStorage.redirectURI="";
                                document.getElementById("redirectUrl").value="";
                            }
                             localStorage.userName=document.getElementById("userName").value;
                             localStorage.redirectURI="";
                      } 
                    }
    

    You can access the variable using localStorage.userName from anywhere in the browser. Worked well for me. ;-)

    Thanks everyone for the help provided..!!

提交回复
热议问题