Web storage for HTML5 local storage

Time:2021-4-7

Before the advent of HTML5, if developers need to store a small amount of data in the client, they can only use cookies to achieve it, but there are several shortcomings in cookies

The size of the cookie under each domain name is limited to 4KB.
· cookies are included in each HTTP request, which results in duplicate data being sent.
The cookie is not encrypted in the process of network transmission, which has security risks.

New web storage function is added in HTML5. The official recommendation of web storage is 5MB for each website, which can store more data than cookie and has more powerful function than cookie. Web storage is now supported by mainstream browsers such as Firefox, opera, chrome and safari.
 
Introduction to web storage

Web storage is divided into session storage and local storage

Session Storage:Similar to session, the lifetime of the data saved by session storage is the same as that of session. When the user session ends, the data saved by session storage disappears.

Local StorageThe data stored in local storage is always local. Unless the user or program makes it clear, the data will exist consistently.

Two properties, sessionstorage and localstorage, are provided in the window object, which represent session storage and local storage respectively. The two functions and usages are almost the same, except that they have different lifetime of data. Storage provides the following properties and methods (take localstorage as an example):

 • localStorage.length : get the number of key value pairs;
 • localStorage.key (index): get the key of the second index;
 • localStorage.getItem (key): get the value corresponding to the specified key;
 • localStorage.setItem (key, value): save the specified key value pair;
 • localStorage.removeItem (key): delete the key value pair corresponding to the specified key;
 • localStorage.clear (): delete all key value pairs.
 
It should be noted that both key and value must be strings. In other words, web storage API can only operate on strings. Then, some data that are not strings can be converted to string format through JSON and other methods before operation.

Web storage uses JSON to store multiple data

Let’s get familiar with the basic usage of related properties and methods through a small program

Enter the basic information of students (including student number, name, grade and gender) and store it in local storage with student number as the key value;
Query the basic information of students through student number;
Display the information of all students;
 
First, we design HTML pages

XML/HTML CodeCopy content to clipboard
  1. <!DOCTYPE html>  
  2. <html lang=“en”>  
  3. <head>  
  4.     <meta charset=“UTF-8”>  
  5.     <title>Web storage of HTML local storage</title>  
  6.     <style type=“text/css”>  
  7.         #content{   
  8.             border: 1px solid #3D19DD;   
  9.             width:600px;   
  10.             text-align:center;   
  11.             padding: 10px 0;   
  12.             margin: 0 auto;   
  13.         }   
  14.         #content input{   
  15.             margin-top: 10px;   
  16.         }   
  17.     </style>  
  18. </head>  
  19. <body>  
  20.     <div id=“content”>  
  21.          <label for=“user_num”>Student number:</label>     
  22.         <input type=“text” id=“user_num” name=“user_num” />  
  23.         <br/>  
  24.         <label for=“user_name”>full name:</label>     
  25.         <input type=“text” id=“user_name” name=“user_name” />     
  26.         <br/>     
  27.         <label for=“grade”>Grade:</label>     
  28.         <input type=“text” id=“grade” name=“grade”/>     
  29.         <br/>     
  30.         <label for=“sex”>Gender:</label>     
  31.         <input type=“text” id=“sex” name=“sex”/>     
  32.         <br/>    
  33.         <input type=“button” onclick=“save()” value=“Add list”/>     
  34.         <hr/>     
  35.         <label for=“search_num”>Enter student number:</label>     
  36.         <input type=“text” id=“search_num” name=“search_num”/>     
  37.         <input type=“button” onclick=“find()” value=“Find student information”/>     
  38.         <p id=“find_result”><br/></p>  
  39.         <hr/>  
  40.          <input type=“button” onclick=“show()” value=Show all>    
  41.          <div id=“list”>     
  42.          </div>    
  43.     </div>     
  44.     <br />             
  45. </body>  
  46. </html>  

Students’ information is saved to local storage through JS. Through analysis, we find that students’ information to be saved includes multiple fields. At this time, we can use the stringify() method of JSON to convert complex objects into strings and store them in web storage. When reading from web storage, we can use the parse() method of JSON to convert them into JSON objects

JavaScript CodeCopy content to clipboard
  1. function save(){     
  2.         var user_num = document.getElementById(“user_num”).value;   
  3.         var user_nameElement = document.getElementById(“user_name”).value;   
  4.         var gradeElement = document.getElementById(“grade”).value;     
  5.         var sexElement = document.getElementById(“sex”).value;   
  6.         var msg = {   
  7.             user_name: user_nameElement,   
  8.             grade: gradeElement,   
  9.             sex: sexElement,   
  10.         };    
  11.         localStorage.setItem(user_num,JSON.stringify(msg));     
  12.     }   
  13.   

We store three pieces of student information in localstorage and view the storage information in localstorage

When using JS to find students’ information through student number, you need to pay attention to that the value you get is a JSON string, which needs to be converted into a JSON object through the parse () method of JSON. The code is as follows:

JavaScript CodeCopy content to clipboard
  1. function find(){     
  2.         var user_num = document.getElementById(“search_num”).value;    
  3.         var str = localStorage.getItem(user_num);    
  4.         var msg = JSON.parse(str);    
  5.         var find_result = document.getElementById(“find_result”);     
  6.         find_result.innerHTML = Student number is:+user_num+Basic information for: Name:+msg.user_name + “, grade: + msg.grade+, gender:+msg.sex;     
  7.     }    
  8.   

Similarly, when displaying all student information, you need to convert the extracted value string into a JSON object

JavaScript CodeCopy content to clipboard
  1. function show(){     
  2.         var list = document.getElementById(“list”);     
  3.         if(localStorage.length>0){     
  4.             var result = “<table border=’1′ style=’width:300px; margin:0 auto;’>”;     
  5.             result += “< tr > < td > student number < / td > < td > name < / td > < td > grade < / td > < td > gender < / td > < / TR >”;     
  6.             for(var i=0;i<localStorage.length;i++){     
  7.                 var user_num = localStorage.key(i);     
  8.                 var str = localStorage.getItem(user_num);     
  9.                 var msg = JSON.parse(str);     
  10.                 result += “<tr><td>”+user_num+“</td><td>”+msg.user_name+“</td><td>”+msg.grade+“</td><td>”+msg.sex+“</td></tr>”;     
  11.             }     
  12.             result += “</table>”;     
  13.             list.innerHTML = result;     
  14.           }else{     
  15.                 list.innerHTML = “No data yet”;     
  16.           }     
  17.     }      
  18.   

The final effect is as follows:

Web storage stores pictures

As we mentioned earlier, local storage only supports string access, so what we need to do is to convert the image into a data URI. One way to do this is to use canvas elements to load images. You can then read the image from canvas as a data URI.
The function to save a picture is as follows:

JavaScript CodeCopy content to clipboard
  1. function setImg(key,src){   
  2.         var img = document.createElement(‘img’);   
  3.         //Trigger the callback function when the image is loaded  
  4.         img.addEventListener(“load”,function(){   
  5.             var imgCanvas = document.createElement(“canvas”),   
  6.             imgContext = imgCanvas.getContext(“2d”);   
  7.         //Make sure that the canvas element is the same size as the image  
  8.         imgCanvas.width = this.width;   
  9.         imgCanvas.height = this.height;   
  10.         //Render image to canvas  
  11.         imgContext.drawImage(this,0,0,this.width,this.height);   
  12.   
  13.         //Take it out in the form of data URL  
  14.         img.crossOrigin = “*”//Prevent cross domain photo retrieval errors  
  15.         var imgAsDataURL = imgCanvas.toDataURL(“image/png”);   
  16.   
  17.         //Save to local storage  
  18.         try{   
  19.             localStorage.setItem(key, imgAsDataURL);   
  20.         }   
  21.         catch(e){   
  22.             alert(“Save failed! Please try again… “);   
  23.         }   
  24.   
  25.         }, false);   
  26.         img.src = src;   
  27.     }   
  28.   

This function receives two parameters, one is the key value, and the other is the path of the image. We can save the image to local storage through setimg (“img1”, “1. JPG”). We can view the storage status of local storage

The code functions obtained and displayed are as follows:

JavaScript CodeCopy content to clipboard
  1. function getImg(key){   
  2.         var srcStr = localStorage.getItem(key);   
  3.         var imgObj = document.createElement(‘img’);   
  4.         imgObj.src = srcStr;   
  5.         document.body.appendChild(imgObj);   
  6.     }   
  7.   

This function only takes one parameter: the key value of the image to be found:

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.