search
HomeWeb Front-endH5 TutorialSummary of H5 localStorage usage

Summary of H5 localStorage usage

Mar 26, 2018 pm 02:32 PM
html5localstorageuse

This time I will bring you a summary of the use of localStorage in H5. What are the precautions when using localStorage? Here are practical cases, let’s take a look.

1. What is localStorage, sessionStorage

In HTML5, a new localStorage feature has been added, this The feature is mainly used as local storage, which solves the problem of insufficient cookie storage space (the storage space of each cookie in the cookie is 4k). Generally, browsers support a size of 5M in localStorage. This is different in different browsers. localStorage will be different.

2. Advantages and limitations of localStorage

Advantages of localStorage

1. LocalStorage expansion Overcoming the 4K limit of cookies

2. LocalStorage will be able to store the first requested data directly locally. This is equivalent to a 5M database for the front-end page. Compared with cookies, it can save bandwidth. However, this is only supported in higher version browsers.

Limitations of localStorage

1. The sizes of browsers are not uniform, and in IE8 or above Only the IE version supports the attribute of localStorage

2. Currently, all browsers limit the value type of localStorage to the string type. This is required for our daily common JSON object types. Some conversions

3. LocalStorage is not readable in the browser's privacy mode

4. LocalStorage essentially reads the string. If stored If there is a lot of content, it will consume memory space and cause the page to become stuck.

5. LocalStorage cannot be crawled by crawlers.

The only difference between localStorage and sessionStorage is that localStorage is a permanent storage, while sessionStorage When the session ends, the key-value pairs in sessionStorage will be cleared

Here we use localStorage to analyze

3. The use of localStorage

LocalStorage browser support:

A special statement here is that if you are using IE browser, then UserData is required As storage, the main explanation here is the content of localStorage, so userData will not be explained too much. In the blogger's personal opinion, there is no need to learn the use of UserData, because the current IE6/IE7 is obsolete. position, and many page development today will involve emerging technologies such as Html5\CSS3, so we generally will not make it compatible when using the above

First of all, when using localStorage, we need to judge Whether the browser supports the localStorage attribute

if(!window.localStorage){
            alert("浏览器支持localstorage");
            return false;
        }else{
            //主逻辑业务
        }

There are three ways to write localStorage. Here we will introduce them one by one

if(!window.localStorage){
            alert("浏览器支持localstorage");
            return false;
        }else{
            var storage=window.localStorage;
            //写入a字段
            storage["a"]=1;
            //写入b字段
            storage.a=1;
            //写入c字段
            storage.setItem("c",3);
            console.log(typeof storage["a"]);
            console.log(typeof storage["b"]);
            console.log(typeof storage["c"]);
        }

The results after running are as follows:

It should be noted here that the use of localStorage also follows the same-origin policy, so different websites cannot directly share the same localStorage

The final result printed on the console is:

I don’t know if readers have noticed that what was just stored was of type int, but it was printed as type of string. This is related to the characteristics of localStorage itself. LocalStorage only supports storage of string type.

Reading of localStorage

if(!window.localStorage){
            alert("浏览器支持localstorage");
        }else{
            var storage=window.localStorage;
            //写入a字段
            storage["a"]=1;
            //写入b字段
            storage.a=1;
            //写入c字段
            storage.setItem("c",3);
            console.log(typeof storage["a"]);
            console.log(typeof storage["b"]);
            console.log(typeof storage["c"]);
            //第一种方法读取
            var a=storage.a;
            console.log(a);
            //第二种方法读取
            var b=storage["b"];
            console.log(b);
            //第三种方法读取
            var c=storage.getItem("c");
            console.log(c);
        }

There are three ways to read localStorage, among which the two officially recommended methods are getItem\setItem to save it. Take, don't ask me why, because I don't know this either

I said before that localStorage is equivalent to a front-end database. The database mainly consists of four steps of adding, deleting, checking and modifying. The reading here and writing are equivalent to the two steps of adding and checking.

Let’s talk about the two steps of deleting and modifying localStorage.

It is easier to understand this step. The idea is Just like re-changing the value of a global variable, here we will take an example to briefly explain

if(!window.localStorage){
            alert("浏览器支持localstorage");
        }else{
            var storage=window.localStorage;
            //写入a字段
            storage["a"]=1;
            //写入b字段
            storage.b=1;
            //写入c字段
            storage.setItem("c",3);
            console.log(storage.a);
            // console.log(typeof storage["a"]);
            // console.log(typeof storage["b"]);
            // console.log(typeof storage["c"]);
            /*分割线*/
            storage.a=4;
            console.log(storage.a);
        }

On the console, we can see that the a key has been changed to 4

localStorage的删除

1、将localStorage的所有内容清除

var storage=window.localStorage;
            storage.a=1;
            storage.setItem("c",3);
            console.log(storage);
            storage.clear();
            console.log(storage);

2、 将localStorage中的某个键值对删除

var storage=window.localStorage;
            storage.a=1;
            storage.setItem("c",3);
            console.log(storage);
            storage.removeItem("a");
            console.log(storage.a);

控制台查看结果

localStorage的键获取

var storage=window.localStorage;
            storage.a=1;
            storage.setItem("c",3);
            for(var i=0;i<storage.length><p style="text-align: left;">使用key()方法,向其中出入索引即可获取对应的键</p>
<p style="text-align: left;"><strong><span style="color:#ff0000">四、localStorage其他注意事项</span></strong></p>
<p style="text-align: left;"> 一般我们会将JSON存入localStorage中,但是在localStorage会自动将localStorage转换成为字符串形式</p>
<p style="text-align: left;">这个时候我们可以使用JSON.stringify()这个方法,来将JSON转换成为JSON字符串</p>
<p style="text-align: left;">示例:</p>
<pre class="brush:php;toolbar:false">if(!window.localStorage){
            alert("浏览器支持localstorage");
        }else{
            var storage=window.localStorage;
            var data={
                name:'xiecanyong',
                sex:'man',
                hobby:'program'
            };
            var d=JSON.stringify(data);
            storage.setItem("data",d);
            console.log(storage.data);
        }

读取之后要将JSON字符串转换成为JSON对象,使用JSON.parse()方法

var storage=window.localStorage;
            var data={
                name:'xiecanyong',
                sex:'man',
                hobby:'program'
            };
            var d=JSON.stringify(data);
            storage.setItem("data",d);
            //将JSON字符串转换成为JSON对象输出
            var json=storage.getItem("data");
            var jsonObj=JSON.parse(json);
            console.log(typeof jsonObj);

打印出来是Object对象

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

H5的存储方式详解

postMessage实现跨域、跨窗口消息传递

The above is the detailed content of Summary of H5 localStorage usage. For more information, please follow other related articles on the PHP Chinese website!

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
Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

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

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment