Table of Contents
Difference between local storage and session storage
Available Web Storage Methods and Properties
最终想法
Home Web Front-end HTML Tutorial Local storage and session storage in JavaScript

Local storage and session storage in JavaScript

Sep 06, 2023 pm 05:41 PM
javascript session storage local storage

Local storage and session storage in JavaScript

Suppose you are creating a web application where users can consume media such as text or images. You want to allow them to write some text that will be accessible even after a page refresh or browser restart. Before the Web Storage API, you had to store information on the backend and reload it on the client side when needed. If you wish to serve information across browsers or devices, this is still the way to go.

However, if you want information that persists across page refreshes or browser restarts to be accessible only on the same browser, then the Web Storage API is a more appropriate tool.

There are two types of web storage implementations, called localStorage and sessionStorage. As you might have guessed from the name, sessionStorage retains information for a single session, while localStorage retains your data even after you restart your browser.

In this tutorial, you will learn all the basics of the Web Storage API, and you will understand how to leverage local storage and session storage to our advantage.

Difference between local storage and session storage

Before we delve into the API, let’s understand the basic differences between local storage and session storage.

  1. localStorage does not expire even if the browser is restarted, while sessionStorage only lasts until the page is refreshed.
  2. localStorage Share between multiple tabs and windows with the same origin. On the other hand, sessionStorage will be different for each tab loading the same web page.

Individual web pages or documents can have their own localStorage and sessionStorage objects. However, they will be independent of each other.

Available Web Storage Methods and Properties

There are five methods available for

localStorage and sessionStorage.

You can use the setItem(key, value) method to store some information in the form of key/value pairs in the storage object. If the key already exists, this method will update its value. Keep in mind that this method requires both keys and values ​​to be strings.

You can use the getItem(key) method to retrieve the information stored for a specific key. If the passed key does not exist, the method will return null.

Suppose you want to delete some information from localStorage or sessionStorage. In this case, you can use the removeItem(key) method and pass the relevant key name to remove the key and its value from the storage.

You can also use the clear() method to clear all keys at once instead of deleting them one at a time from storage.

There is also a key(index) method which accepts an integer as the key index and returns the key name at that specific index. The important thing to remember here is that the order of keys is defined by the user agent.

Finally, there is a length property that you can use to get the number of data items stored in a given storage object.

You can use the length property with the key() method and the getItem() method to access localStorage or ## The values ​​of all keys in #sessionStorage.

Here are some examples using all of these methods:

/* Save some key-value pairs */
localStorage.setItem("artist", "Monty Shokeen");
localStorage.setItem("website", "tutsplus.com");
localStorage.setItem("font", "Righteous");
localStorage.setItem("stroke_width", "4");
localStorage.setItem("color", "#FF5722");

/* Access stored values */
console.log(localStorage.getItem("color"));
// Outputs: #FF5722

console.log(localStorage.getItem("stroke_width"));
// Outputs: 4

/* Iterate over keys */
for (let i = 0; i < localStorage.length; i++) {
  console.log(`${localStorage.key(i)} : ${localStorage.getItem(localStorage.key(i))}`);
}
/*
stroke_width : 4
font : Righteous
website : tutsplus.com
color : #FF5722
artist : Monty Shokeen
*/

/* Removing keys from storage */
localStorage.removeItem("website"); 
localStorage.getItem("website"); 
// Outputs: null
Copy after login

Practical application of local storage

Let's do something practical with all the knowledge we've gained. We will create a simple drawing application where the user can save data in local storage for future retrieval.

Our drawing application will be very simple. We will have a canvas where the user can draw concentric circles of random radii. The minimum and maximum values ​​of the radius will be determined by the input fields they populate. We will also have a button to clear the canvas once we have drawn too many circles. This is our mark:

<canvas id="canvas" width="810" height="400"></canvas>
<form>
  <label for="min-rad">Min. Radius</label>
  <input type="number" name="min-rad" id="min-rad" min="4"></input>
  <br>
  <label for="max-rad">Max. Radius</label>
  <input type="number" name="max-rad" id="max-rad" min="20"></input>
  <br>
  <button type="button" id="clear">Clear Canvas</button>
</form>
Copy after login

We will store three pieces of information in local storage: minimum radius, maximum radius and the state of the canvas. Remember that local storage can only store information as strings. Input field values ​​can be automatically converted to strings. However, we need to get the status of the canvas as a string using the

toDataURL() method. This method returns a string containing the URL of the requested data.

We will attach event listeners to all elements on the page: the canvas's

mousedown event listener, the input element's change event listener, and the button's click Event listener. Let's start with some initialization code and event listeners for the form fields.

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

const minElem = document.querySelector("input#min-rad");
const maxElem = document.querySelector("input#max-rad");
const clearBtn = document.querySelector("button#clear");

let min_radius = 10;
let max_radius = 30;

minElem.addEventListener("change", function(event) {
  min_radius = parseInt(event.target.value);
  localStorage.setItem("min-radius", min_radius);
});

maxElem.addEventListener("change", function(event) {
  max_radius = parseInt(event.target.value);
  localStorage.setItem("max-radius", max_radius);
});

clearBtn.addEventListener("click", function(event) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  let image_data = canvas.toDataURL();
  localStorage.setItem("image-data", image_data);
});
Copy after login

默认情况下,我们将最小和最大半径值分别设置为 10 和 30 像素。最小和最大半径输入字段的更改事件侦听器将解析输入的值,然后将这些值存储在本地存储中。

在按钮的单击事件侦听器回调中,我们首先清除画布,然后使用 toDataUrl() 方法将此清除状态保存到本地存储。

这是在画布上侦听 mousedown 事件的代码。

canvas.addEventListener('mousedown', function(event) {
    const canvas_rect = event.target.getBoundingClientRect();
    const pos_x = event.clientX - canvas_rect.left;
    const pos_y = event.clientY - canvas_rect.top;
  
    for(let i = 0; i < 10; i++) {
      let radius = min_radius + Math.floor(Math.random()*(max_radius - min_radius));
      ctx.beginPath();
      ctx.arc(pos_x, pos_y, radius, 0, 2 * Math.PI);
      ctx.stroke();
    }
  
    let image_data = canvas.toDataURL();
    localStorage.setItem("image-data", image_data);
});
Copy after login

让我们来分解一下。我们首先计算用户在画布上单击的确切位置。这是通过从单击位置的 x 坐标减去画布边界矩形的 left 属性的值来确定的。我们做同样的事情来获取点击的垂直位置。

之后,我们创建一个 for 循环,在画布上绘制十个同心圆。半径设置为受最小和最大约束的随机值。最后,就像按钮的点击监听器一样,我们将画布状态保存在本地存储中。每次点击都会发生这种情况,以便我们能够及时了解最新的画布状态。

现在我们唯一要做的就是从本地存储中恢复值以供重新加载或重新启动时使用。我们使用以下代码来完成此操作:

window.addEventListener("DOMContentLoaded", (event) => {
  if (localStorage.getItem("image-data")) {
    var img = new Image();
    img.onload = function () {
      ctx.drawImage(img, 0, 0);
    };
    img.src = localStorage.getItem("image-data");
  }

  if (localStorage.getItem("min-radius")) {
    min_radius = parseInt(localStorage.getItem("min-radius"));
  }

  if (localStorage.getItem("max-radius")) {
    max_radius = parseInt(localStorage.getItem("max-radius"));
  }

  minElem.value = min_radius;
  maxElem.value = max_radius;
});
Copy after login

这里最复杂的部分是将图像数据从本地存储恢复到画布。为此,我们首先创建 HTMLImageElement 的新实例,然后侦听其 onload 事件,以便在画布上绘制加载的图像。

以下 CodePen 演示将向您展示我们的绘图应用程序的实际运行情况。首先尝试单击画布绘制一些圆圈或将半径设置为您喜欢的值。

现在,我们在教程中使用localStorage,这意味着即使浏览器重新启动我们的数据也将是安全的。您可以尝试将其替换为 sessionStorage 以仅在页面刷新期间保留信息。

最终想法

在本教程中,我们介绍了 JavaScript 中 localStoragesessionStorage 的基础知识。您现在应该能够使用 Web Storage API 在浏览器存储中存储和检索信息。正如我们在此处创建绘图应用程序时看到的那样,该 API 有很多应用程序。您还可以使用它在本地文本编辑器中实现内容保存功能。

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

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles