search
HomeWeb Front-endHTML TutorialLocal storage and session storage in JavaScript

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

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>

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);
});

默认情况下,我们将最小和最大半径值分别设置为 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);
});

让我们来分解一下。我们首先计算用户在画布上单击的确切位置。这是通过从单击位置的 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;
});

这里最复杂的部分是将图像数据从本地存储恢复到画布。为此,我们首先创建 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
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
What is the difference between an HTML tag and an HTML attribute?What is the difference between an HTML tag and an HTML attribute?May 14, 2025 am 12:01 AM

HTMLtagsdefinethestructureofawebpage,whileattributesaddfunctionalityanddetails.1)Tagslike,,andoutlinethecontent'splacement.2)Attributessuchassrc,class,andstyleenhancetagsbyspecifyingimagesources,styling,andmore,improvingfunctionalityandappearance.

The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

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 Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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.