Home>Article>Web Front-end> 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, calledlocalStorage
andsessionStorage
. As you might have guessed from the name,sessionStorage
retains information for a single session, whilelocalStorage
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.
Before we delve into the API, let’s understand the basic differences between local storage and session storage.
localStorage
does not expire even if the browser is restarted, whilesessionStorage
only lasts until the page is refreshed.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 ownlocalStorage
andsessionStorage
objects. However, they will be independent of each other.
localStorage
andsessionStorage
.
You can use thesetItem(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 thegetItem(key)
method to retrieve the information stored for a specific key. If the passed key does not exist, the method will returnnull
.
Suppose you want to delete some information fromlocalStorage
orsessionStorage
. In this case, you can use theremoveItem(key)
method and pass the relevant key name to remove the key and its value from the storage.
You can also use theclear()
method to clear all keys at once instead of deleting them one at a time from storage.
There is also akey(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 alength
property that you can use to get the number of data items stored in a given storage object.
You can use thelength
property with thekey()
method and thegetItem()
method to accesslocalStorage
or ## The values of all keys in #sessionStorage.
/* 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: nullPractical 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:
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.
mousedownevent listener, the input element's
changeevent listener, and the button's
clickEvent 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 中localStorage
和sessionStorage
的基础知识。您现在应该能够使用 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!