search
HomeWeb Front-endH5 TutorialHTML5 client data storageWeb Storage—localStorage and sessionStorage


HTML5 provides a new method of storing data on the client side Web Storage
Similar to Cookie in HTML4
But it is much more powerful

Cookie

Let’s briefly review the cookies used before

Cookies store data on the user’s device. The amount of data stored is small, only 4KB
Yes Detect whether cookies are enabled through navigator.cookieEnabled

  • Set cookies document.cookie = 'key=value';

  • Get cookie document.cookie;

  • Delete cookie document.cookie = "key=value;max-age=0";

  • Set max-age storage perioddocument.cookie = "key=value;max-age=1000"; // 1000 seconds

  • Set expires storage period

var timestamp = (new Date()).getTime() + 10000;var expires = new Date(timestamp).toGMTString();
//或toUTCStringdocument.cookie = "key=value;expires="+expires;
  • Get specific cookie value

function getCookie(name) {
    var name = name + "=";    
    var ary = document.cookie.split(';');    
    for(var i = 0; i < ary.length; i++){        
    var c = ary[i];        
    while (c.charAt(0) == &#39; &#39;){
          c = c.substring(1);
        }        
        if (c.indexOf(name) != -1){          
        return c.substring(name.length, c.length);
        }
    }    return "";
}

Web Storage

Web Storage is divided into two types
localStorage and sessionStorage
The difference is:

  • localStorage stores permanent data unless manually deleted

  • sessionStorage stores temporary data and will disappear when the window is closed

Easy to use

Web Storage can only store string data
I think they can be understood as JSON
The usage methods are similar, taking localStorage as an example

localStorage.name = &#39;payen&#39;;
localStorage.info = JSON.stringify({name: &#39;payen&#39;, age: 20});
console.log(localStorage.name);
console.log(JSON.parse(localStorage.info));

The name of the data to be stored is the attribute name of localStorage
Ordinary strings can be stored normally That’s it
Object data can be converted to string format using JSON.stringify()
When used, JSON.parse() can be used to convert it back to object format
(If the object is stored directly, it will Forced to be converted into a string "[object Object]")


To delete the data, just delete it

delete localStorage.name;delete localStorage.info;

If you do not delete it, the data in localStorage will always exist for you. The browser

API

localStorage and sessionStorage also provide a simple API
Similar to a client database
(APIs are the same)
Commonly used There are the following:

  • Save data setItem(key, value)

  • Read data getItem(key)

  • Delete a single data removeItem(key)

  • Clear all data clearItem()

  • Get the data index key(index)

Example

Through this, we can write a simple address book

<p id="container">
    <br>
    <label for="username">姓名:</label>
    <input type="text" id="username" name="username">
    <br>
    <label for="mobilephone">手机:</label>
    <input type="text" id="mobilephone" name="mobilephone">
    <br><br>
    <input type="button" onclick="add()" id="add" value="增加联系人">
    <br><br>
    <hr>
    <label for="search">输入姓名:</label>
    <input type="text" id="search" name="search">
    <br><br>
    <input type="button" onclick="find()" id="find" value="查找手机号">
    <p id="result"><br></p></p>
#container {    
border: 2px solid gray;    
width: 320px;    
text-align:center;}

HTML5 client data storageWeb Storage—localStorage and sessionStorage

##It is implemented in JavaScript These two functions

var user = document.getElementById(&#39;username&#39;),
    phone = document.getElementById(&#39;mobilephone&#39;),
    search = document.getElementById(&#39;search&#39;),
    result = document.getElementById(&#39;result&#39;);var add = function(){
    var u = user.value,
        p = phone.value,
        l = localStorage.length;    if(u !== &#39;&#39; && p !== &#39;&#39;){
        localStorage.setItem(u, p);
        user.value = &#39;&#39;;
        phone.value = &#39;&#39;;
        alert(&#39;添加成功&#39;);
    }
};var find = function(){
    var s = search.value,
        r = localStorage.getItem(s);    if(s !== &#39;&#39; && r){
        result.innerHTML = r;
    }
};

HTML5 client data storageWeb Storage—localStorage and sessionStorage

Enter the name and mobile phone number to add a contact

Then enter the contact name below and we can find the mobile phone number

HTML5 client data storageWeb Storage—localStorage and sessionStorage


Of course this address book is very simple

You can also add it to display all the information in the address book
Delete contact function, etc.

Cookies and Web Storage Difference

Finally let’s talk about the difference between Html5’s Web Storage and Html4’s cookie

FeaturesCookieWeb StorageLife cycle is generally generated by the server and sets the time; generated by the browser, it is closed by default and the browser failslocal : Save permanently if not cleared; session: Close the page or the browser is invalidData size4KBOfficial recommendation 5MBCommunicationCarried in the HTTP header (excessive use may cause performance problems)Only stored in the browser, does not participate in communicationUsingThe native interface is not friendly and needs to be encapsulated manuallyThe native interface is friendly
The above is the HTML5 client data storage Web Storage—localStorage and sessionStorage content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

Is h5 same as HTML5?Is h5 same as HTML5?Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.