search
HomeWeb Front-endJS TutorialThe difference between local storage, session storage and cookies in JavaScript

JavaScript 中本地存储、会话存储和 Cookie 之间的区别

JavaScript provides three mechanisms for storing data on the client side - cookies, session storage and local storage. Each mechanism has advantages and disadvantages.

Local storage is the latest mechanism. It allows large amounts of data to be stored, but the data is not deleted when the browser is closed. Local storage is useful for storing data that users need to access later, such as offline data.

Session StorageSimilar to cookies, but the data is only stored for the current session. This means the data will be deleted when the user closes the browser. Session storage is useful for storing sensitive data such as login credentials.

Cookie is the oldest and most famous mechanism. They are simple to use and well supported by browsers. However, they are limited to 4KB of data and are often used to store insensitive data such as user preferences.

In this tutorial, we will cover each of them in detail.

Local Storage

Most web applications these days require some type of user input, whether it's a username, shipping address, or even just a preference setting. That input is then typically sent to a server somewhere for processing and storage. But what if your application requires data to be stored locally on the user's computer? This is where local storage comes in.

Local storage is a type of web storage that allows JavaScript to store and access data directly in the browser. This is particularly useful for storing data that you want to keep even if the user closes the browser, such as preferences or settings.

Data in local storage is stored in key/value pairs. The key is like the name of the data and the value is like the actual data itself. You can think of it as a variable in JavaScript. To store data in local storage, you first need to create a key. You can then store any data you want under that key.

To create a key, use the setItem() method. This method takes two parameters, the first is the key and the second is the value to be stored.

localStorage.setItem('key', 'value');

Now that you have the key, you can store any data you want under that key. The data you store can be any data type supported by JavaScript, including strings, numbers, objects, and arrays.

To store data, use the setItem() method again. This time, you pass in the key as the first parameter and the data to be stored as the second parameter.

localStorage.setItem('key', 'value');

To retrieve data from local storage, use the getItem() method. This method takes a key as a parameter and returns the data stored under that key.

localStorage.getItem('key');

If you want to remove an item from local storage, use the removeItem() method. This method takes a key as parameter and deletes the data stored under that key.

localStorage.removeItem('key');

Session Storage

Session Storage is a type of web storage that allows web applications to store data locally in the user's browser. Unlike cookies, the data stored in session storage is specific to the site that created it, and the data is not shared with other sites.

Session storage is a new feature introduced in HTML5 that allows you to store data locally in the user's browser. Unlike cookies, the data stored in session storage is specific to the site that created it, and the data is not shared with other sites.

Session storage is a way of storing data on the client side of an application. It is similar to Local storage, but with some key differences -

  • Session storage data is only available to the site that created it.

  • Session storage data is not shared with other sites.

  • Session storage data is not persistent, meaning it is only available during the user session.

  • Session storage data is specific to the browser tab that created it.

Session storage is a great way to improve the performance of your web application by reducing the amount of data that needs to be transferred between the client and server. It can also be used to store data in a more secure manner, as the data is not stored in cookies that can be accessed by third-party websites.

To use session storage in a web application, you need to use a sessionStorage object. This object provides access to the current session storage.

sessionStorage object has two methods

setItem() - This method sets a key/value pair session storage.

sessionStorage.setItem("name", "tutorialsPoint");

getItem() - This method retrieves the value of the key from the session storage.

var name = sessionStorage.getItem("name");

sessionStorage object has some other properties -

  • length - This property returns the number of key/value pairs in the session storage.

  • key() - This method accepts an index as a parameter and returns the key at that index in the session storage

Session storage is a great way to improve web application performance and store data in a more secure way.

Cookie 是存储在用户计算机上的一小段数据。 Cookie 用于存储有关用户的信息,例如用户的姓名、密码和偏好设置。

Cookie 是使用 document.cookie 属性创建的。此属性用于设置、获取和删除 Cookie。

使用 setItem() 方法设置 Cookie。该方法接受两个参数,cookie的名称和cookie的值。

cookie的名称用于标识cookie,值是要存储在cookie中的信息。 cookie。

以下代码设置一个名为“name”和值“tutorialsPoint”的 cookie。

document.cookie = "name=tutorialsPoint";

使用 getItem() 方法读取 Cookie。此方法接受 cookie 的名称作为参数并返回 cookie 的值。

如果 cookie 不存在,getItem() 方法将返回 null。

以下代码读取“name”cookie 并将值存储在“user”变量中。

var user = document.cookie.getItem("name");

与本地存储和会话存储相比,cookie 的一个优点是它们可以设置为在特定时间过期,这使得它们成为存储不应长期保留的数据(例如会话 ID)的不错选择。

下表突出显示了本地存储、会话存储和 Cookie 之间的主要区别 -

本地存储 会话存储 Cookie
允许存储10MB的数据。 允许存储5MB的数据。 存储容量限制为4KB数据。
关闭浏览器时不会删除存储的数据。 存储数据仅用于会话并会在浏览器关闭时被删除。 数据可以设置为在某个时间过期。
本地存储对于存储用户稍后需要访问的数据,例如离线数据。 会话存储是提高 Web 应用程序性能的好方法。 Cookie 是一个不错的选择用于存储不应该长时间保留的数据,例如会话 ID。
这对于存储即使用户关闭也希望保留的数据特别有用浏览器,例如首选项或设置。 会话存储对于存储敏感数据(例如登录凭据)非常有用。 Cookie 通常用于存储不敏感的数据,例如用户偏好
本地存储是HTML5中引入的新功能 会话存储是HTML5中引入的新功能HTML5 Cookie 是最古老的 (HTML4) 和最著名的机制。
数据是不随客户端请求发送到服务器。 数据不随客户端请求发送到服务器 数据随客户端请求发送到服务器
数据存储在浏览器和系统上。 数据仅存储在浏览器上。 数据仅存储在浏览器上。

结论

在本教程中,我们讨论了本地存储、会话存储之间的区别和饼干。我们已经看到了从该存储中存储和检索数据的不同方法。 本地存储是最新的机制。它允许存储更大量(10MB)的数据,但关闭浏览器时数据不会被删除。 会话存储与cookie类似,但仅存储当前会话的数据。这意味着当用户关闭浏览器时数据将被删除。 Cookie 是最古老、最著名的机制。它们使用简单并且受到浏览器的良好支持。但是,它们仅限于 4KB 的数据,并且通常用于存储不敏感的数据,例如用户首选项。

The above is the detailed content of The difference between local storage, session storage and cookies in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor