search
HomeWeb Front-endHTML TutorialDetailed explanation of HTMl5 storage methods sessionStorage and localStorage

This article mainly introduces the detailed explanation of HTMl5 storage methods sessionStorage and localStorage. It has certain reference value. Now I share it with you. Friends in need can refer to it.

Web Storage in html5 includes Two storage methods: sessionStorage and localStorage. sessionStorage is used to locally store data in a session. These data can only be accessed by pages in the same session and the data will be destroyed when the session ends. Therefore sessionStorage is not a persistent local storage, only session-level storage. LocalStorage is used for persistent local storage. Unless the data is actively deleted, the data will never expire.
1. The difference between web storage and cookies
The concept of Web Storage is similar to that of cookies. The difference is that it is designed for larger capacity storage. The size of the cookie is limited, and the cookie will be sent every time you request a new page, which wastes bandwidth. In addition, the cookie needs to specify a scope and cannot be called across domains.
In addition, Web Storage has setItem, getItem, removeItem, clear and other methods. Unlike cookies, front-end developers need to encapsulate setCookie and getCookie themselves.
But Cookies are also indispensable: Cookies are used to interact with the server and exist as part of the HTTP specification, while Web Storage is only created to "store" data locally (Correction from @otakustay)
2. Browser support for html5 web storage
Except for IE7 and below, other standard browsers are fully supported (ie and FF need to be in the web server) Run), it is worth mentioning that IE always does good things. For example, UserData in IE7 and IE6 is actually a solution for javascript local storage. Through simple code encapsulation, all browsers can be unified to support web storage.
To determine whether the browser supports localStorage, you can use the following code:

Copy the code

The code is as follows:

if(window.localStorage){
    alert("浏览支持localStorage") 
}
else
{    
    alert("浏览暂不支持localStorage") 
} 
//或者 if(typeof window.localStorage == 'undefined'){ alert("浏览暂不支持localStorage") }


3. LocalStorage and sessionStorage operations
Both localStorage and sessionStorage have the same operation methods, such as setItem, getItem and removeItem, etc.
Methods of localStorage and sessionStorage:
setItem stores value
Purpose: Store value in the key field
Usage: .setItem(key, value)
Code example:

Copy Code

##The code is as follows:

sessionStorage.setItem("key", "value");
localStorage.setItem("site", "js8.in");

getItem gets value

Purpose: Get the value stored locally for the specified key
Usage: .getItem(key)
Code example:

Copy code

The code is as follows:

var value = sessionStorage.getItem("key");  
var site = localStorage.getItem("site");

removeItemDelete key

Purpose : Delete the value stored locally for the specified key
Usage: .removeItem(key)
Code example:

Copy code

The code is as follows:

sessionStorage.removeItem("key");  
localStorage.removeItem("site");

clear clear all key/value

Purpose: clear all key/value
Usage:.clear()
Code example:

Copy code

The code is as follows:

sessionStorage.clear();  
localStorage.clear();

4. Other operation methods: point operation and []
Web Storage can not only use its own setItem, getItem, etc. for convenient access, but can also use the dot (.) operator and [] like ordinary objects to store data, like the following code:

Copy code

The code is as follows:

var storage = window.localStorage; storage.key1 = "hello"; 
storage["key2"] = "world"; 
console.log(storage.key1); 
console.log(storage["key2"]);

5. The key and length attributes of localStorage and sessionStorage Implementing traversal
The key() and length provided by sessionStorage and localStorage can easily implement traversal of stored data, such as the following code:

Copy code

The code is as follows:

var storage = window.localStorage; 
for (var i=0, len = storage.length; i  <  len; i++)
{
    var key = storage.key(i);     
    var value = storage.getItem(key);     
    console.log(key + "=" + value); 
}

6. Storage event
Storage also provides storage events, which can be triggered when the key value changes or is cleared. storage event, for example, the following code adds a listener for storage event changes:

Copy code

The code is as follows:

if(window.addEventListener){  
    window.addEventListener("storage",handle_storage,false); 
}
else if(window.attachEvent)
{  
    window.attachEvent("onstorage",handle_storage); 
} 
function handle_storage(e){
    if(!e){e=window.event;}  
}

The specific properties of the storage event object are as follows:

Property Type Description
key String The named key that was added, removed, or moddified
oldValue Any The previous value(now overwritten), or null if a new item was added
newValue Any The new value, or null if an item was added
url/uri String The page that called the method that triggered this change
相关推荐:

HTML5所有标签汇总及标签意义解释


The above is the detailed content of Detailed explanation of HTMl5 storage methods sessionStorage and localStorage. 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
localstorage为什么不安全localstorage为什么不安全Oct 10, 2023 pm 05:38 PM

localstorage不安全的原因是数据不加密、XSS攻击、CERF攻击、容量限制等。详细介绍:1、数据不加密,localstorage是一个简单的键值对存储系统,它将数据以明文形式存储在用户的浏览器中,这意味着任何人都可以轻松地访问和读取存储在localstorage中的数据,如果敏感信息存储在localstorage中,那么黑客或恶意用户可以轻松地获取这些信息等等。

html设置缓存三种方法是什么html设置缓存三种方法是什么Feb 22, 2024 pm 10:57 PM

HTML设置缓存的三种方法是什么?在Web开发中,为了提高用户访问速度和减轻服务器负载,我们可以通过设置缓存来减少网页加载时间。接下来,我将为您详细介绍三种常用的HTML设置缓存的方法,并提供具体的代码示例。方法一:通过HTTP响应头设置缓存HTTP响应头中的"Cache-Control"和"Expires"是设置缓存的两个常用属性。通过设置这两个属性,可以

NEXTAUTH_SECRET 变量与用于生成 JWT 令牌的后端机密相同吗?NEXTAUTH_SECRET 变量与用于生成 JWT 令牌的后端机密相同吗?Feb 08, 2024 pm 11:09 PM

我正在使用NextJS编写前端应用程序,并使用nextauth进行身份验证(电子邮件、密码登录)。我的后端是用GoLang编写的不同代码库,因此当用户登录时,它将向Golang后端端点发送请求,并返回JWT令牌,该令牌生成如下所示:config:=config.GetConfig()atClaims:=jwt.MapClaims{}atClaims["authorized"]=trueatClaims["id"]=userIdatClaims["email"

html5有什么优点html5有什么优点Apr 22, 2024 am 11:09 AM

HTML5的主要优点包括:语义化标记:清晰地传达内容结构和含义。多媒体支持:原生播放视频和音频。画布:创建动态图形和动画。本地存储:客户端存储数据并跨会话访问。地理定位:获取用户地理位置信息。WebSockets:浏览器和服务器之间的持续连接。移动友好:适用于各种设备。安全性:CSP和CORS保护免受网络威胁。易用性:易于学习和使用。支持:广泛支持所有主要浏览器和设备。

localstorage有哪些方法localstorage有哪些方法Oct 10, 2023 pm 01:55 PM

localstorage的方法有:1、setItem,将数据存储到localstorage中;2、getItem,从localstorage中检索数据;3、removeItem,从localstorage中删除指定数据;4、clear,清空localstorage中所有数据;5、key,获取localstorage中指定索引位置键名;6、length,获取存储的数据的数量等等。

保护用户隐私和数据安全:使用SessionStorage存储用户数据的方法保护用户隐私和数据安全:使用SessionStorage存储用户数据的方法Jan 11, 2024 pm 02:50 PM

使用SessionStorage存储用户数据:如何保护用户隐私和数据安全?随着互联网的发展,越来越多的网站和应用程序需要存储用户数据,以提供个性化的服务和更好的用户体验。然而,用户数据的隐私和安全问题也日益凸显。为了解决这一问题,SessionStorage成为了一个理想的解决方案。本文将介绍如何使用SessionStorage存储用户数据,并探讨如何保护用

哪些浏览器支持sessionstorage哪些浏览器支持sessionstorageNov 07, 2023 am 09:39 AM

大多数现代浏览器都支持 SessionStorage,包括“Google Chrome ”、“Mozilla Firefox”、“Safari”、“Microsoft Edge”和“Opera”五种。

localstorage使用方法localstorage使用方法Nov 27, 2023 am 10:47 AM

localstorage使用方法:1、存储数据到localstorage;2、从localStorage中检索数据;3、 更新已存储的数据;4、删除数据;5、清空localstorage;6、检查localstorage是否可用;7、存储和检索复杂对象。详细介绍:1、存储数据到localstorage,要将数据存储到localStorage中等等。

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment