search
HomeWeb Front-endH5 TutorialDetailed introduction to localstorage in html5 (picture)

localstorage has two types in the browser's API: localStorage and sessionStorage, which exist in the window object : localStorage corresponds to window.localStorage, and sessionStorage corresponds window.sessionStorage. . Next, this article will introduce to you the relevant information of localstorage of html5. Friends who need it can refer to

HTML API

localstorage has two browser APIs: localStorage and sessionStorage, which exist in the window object: localStorage corresponds to window.localStorage, and sessionStorage corresponds to window.sessionStorage.

The difference between localStorage and sessionStorage mainly lies in their lifetime.

Basic use of methods

localStorage.setItem("b","isaac");//设置b为"isaac"
var b = localStorage.getItem("b");//获取b的值,为"isaac"
var a = localStorage.key(0); // 获取第0个数据项的键名,此处即为“b”
localStorage.removeItem("b");//清除b的值
localStorage.clear();//清除当前域名下的所有localstorage数据

Scope

The scope here refers to: how to isolate localStorage between different pages (it is impossible to read Tencent’s localStorage on Baidu pages) Yeah, hahaha).

localStorage can read/modify the same localStorage data as long as it is under the same protocol, the same host name, and the same port.

sessionStorage is more stringent than localStorage. In addition to the protocol, host name, and port, it also requires being in the same window (that is, the tab page of the browser).

Lifetime

Theoretically, localStorage is permanently valid, that is, it will not disappear if it is not actively cleared, even if the saved data exceeds If the size specified by the browser is exceeded, the old data will not be cleared and only an error will be reported. However, it should be noted that in the browser on the mobile device or the WebView used by each Native App, localStorage is unreliable and may fail due to various reasons (such as exitingApp, network switching , insufficient memory, etc.) are cleared.

As the name suggests, the lifetime of sessionStorage is similar to a session. As long as the browser is closed (including the browser tab), it will be cleared. Since the lifetime of sessionStorage is too short, its application scenarios are very limited, but on the other hand, it is not prone to abnormal situations and is relatively reliable.

Data structure

localstorage is a standard key-value pair (Key-Value, KV for short) Data type, Simple but easy to extend. As long as the object you want to store in localstorage is converted into a string using a certain encoding method, it can be easily supported. For example: convert the object into a json string to store the object; convert the picture into DataUrl (base64) to store the picture. In addition, for key-value data types, the feature "the key is unique" is also very important. If you assign the same key repeatedly, the last value will be overwritten.

Expiration time

Unfortunately, localstorage does not natively support setting the expiration time. If you want to set it, you can only encapsulate it yourself. A layer of logic is implemented:

function set(key,value){
  var curtime = new Date().getTime();//获取当前时间
  localStorage.setItem(key,JSON.stringify({val:value,time:curtime}));//转换成json字符串序列
}
function get(key,exp)//exp是设置的过期时间
{
  var val = localStorage.getItem(key);//获取存储的元素
  var dataobj = JSON.parse(val);//解析出json对象
  if(new Date().getTime() - dataobj.time > exp)//如果当前时间-减去存储的元素在创建时候设置的时间 > 过期时间
  {
    console.log("expires");//提示过期
  }
  else{
    console.log("val="+dataobj.val);
  }
}

Capacity limit

The current industry is basically unified at 5M, which is already larger than cookie The 4K version of s is much larger, so use it sparingly.

Domain name restrictions

Due to the security policy of the browser, localstorage cannot cross domain, nor can it be used by sub-domains. The domain name inherits the localstorage data of the parent domain name. This is quite different from cookies.

Exception handling

Localstorage is not completely stable in the current browser environment, and various bugs may occur. You must consider exception handling. I personally think that localstorage is just an optimization method for resource localization. The use of localstorage cannot reduce the usability of the program. I am absolutely opposed to exception handling that only outputs an error message in the console. Localstorage exception handling generally uses try/catch to catch/handle exceptions.

How to test whether the user's current browser supports localstorage

The current common practice is to detect whether window.localStorage exists, but some browsers There are bugs. Although localstorage is "supported", low-level bugs such as being unable to setItem() may even occur in the actual process. Therefore, I suggest that you can determine whether the browser supports localstorage by setting/getting a test data in the try/catch structure to see if there are exceptions. Of course, remember to delete the test data after the test is completed.

Browser Compatibility

##How Debugging

Resources - Local Storage panel and Resources - Session in chrome developer tools In the Storage panel, you can see the localstorage data under the current domain name.

setItem() cannot be repeated on ios devices

In addition, sometimes strange behavior occurs when setting setItem() on iPhone/iPad QUOTA_EXCEEDED_ERR error. Generally, removeItem() before setItem will be ok.

The above is the detailed content of Detailed introduction to localstorage in html5 (picture). 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
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.

What is the function of H5?What is the function of H5?Apr 07, 2025 am 12:10 AM

H5, or HTML5, is the fifth version of HTML. It provides developers with a stronger tool set, making it easier to create complex web applications. The core functions of H5 include: 1) elements that allow drawing graphics and animations on web pages; 2) semantic tags such as, etc. to make the web page structure clear and conducive to SEO optimization; 3) new APIs such as GeolocationAPI support location-based services; 4) Cross-browser compatibility needs to be ensured through compatibility testing and Polyfill library.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment