Javascript 简明教程
JavaScript - Storage API
What is Web Storage API?
JavaScript 中的 Web 存储 API 允许我们在用户本地系统或硬盘中存储数据。在 JavaScript 中引入存储 API 之前,cookie 被用来将数据存储在用户的浏览器中。
The web storage API in JavaScript allows us to store the data in the user’s local system or hard disk. Before the storage API was introduced in JavaScript, cookies were used to store the data in the user’s browser.
cookie 的主要问题是,每当浏览器请求数据时,服务器都必须发送数据并将其存储在浏览器中。有时,攻击者还可能攻击和窃取数据。
The main problem with the cookies is that whenever browsers request the data, the server must send it and store it in the browser. Sometimes, it can also happen that attackers can attack and steal the data.
对于存储 API,我们可以将用户数据存储在浏览器中,这些数据仅限于用户的设备。
In the case of the storage API, we can store the user’s data in the browsers, which remains limited to the user’s device.
JavaScript 包含两个不同的对象,用于将数据存储在本地。
JavaScript contains two different objects to store the data in the local.
-
localStorage
-
sessionStorage
在此,我们解释了本地存储和会话存储。
Here, we have explained the local and session storage.
The Window localStorage Object
localStorage 对象允许您以键值对格式将数据本地存储在用户的浏览器中。
The localStorage object allows you to store the data locally in the key-value pair format in the user’s browser.
您最多可以在本地存储中存储 5 MB 的数据。
You can store a maximum of 5 MB data in the local storage.
无论您在本地存储中存储什么数据,它都不会过期。但是,您可以使用 removeItem() 方法来移除特定项,或使用 clear() 来从本地存储中移除所有项。
Whatever data you store into the local storage, it never expires. However, you can use the removeItem() method to remove the particular or clear() to remove all items from the local storage.
Syntax
我们可以遵循以下语法从浏览器的本地存储中设置和获取项。
We can follow the syntax below to set and get items from the browser’s local storage.
localStorage.setItem(key, value); // To set key-value pair
localStorage.getItem(key); // To get data using a key
在上述语法中,setItem() 方法在本地存储中设置该项,而 getItem() 方法用于使用其键从本地存储中获取该项。
In the above syntax, the setItem() method sets the item in the local storage, and the getItem() method is used to get the item from the local storage using its key.
Example
在下面的代码中,我们在 setItem() 函数内部将“fruit”设置为键,将“Apple”设置为本地存储中的值。当用户单击该按钮时,我们调用 setItem() 函数。
In the below code, we set the 'fruit' as a key and 'Apple' as a value in the local storage inside the setItem() function. We invoke the setItem() function when users click the button.
在 getItem() 函数中,我们从本地存储中获取“fruit”键的值。
In the getItem() function, we get the value of the 'fruit' key from the local storage.
用户可以首先单击设置项按钮,然后获取该项以从本地存储中获取键值对。
Users can click the set item button first and then get the item to get the key-value pair from the local storage.
<html>
<body>
<button onclick = "setItem()"> Set Item </button>
<button onclick = "getItem()"> Get Item </button>
<p id = "demo"> </p>
<script>
const output = document.getElementById('demo');
function setItem() {
localStorage.setItem("fruit", "Apple");
}
function getItem() {
const fruitName = localStorage.getItem("fruit");
output.innerHTML = "The name of the fruit is: " + fruitName;
}
</script>
</body>
</html>
localStorage 不允许您存储对象、函数等。所以,您可以使用 JSON.stringify() 方法将对象转换成字符串,并将其存储在本地存储中。
The localStorage doesn’t allow you to store the objects, functions, etc. So, you can use the JSON.stringify() method to convert the object into a string and store it in the local storage.
Example: Storing the object in the local storage
在下面的代码中,我们创建了动物对象。然后,我们使用 JSON.stringify() 方法将其转换成字符串并将其存储为“animal”对象的的值。
In the below code, we have created the animal object. After that, we used the JSON.stringify() method to convert it into the string and store it as a value of the 'animal' object.
用户可以单击设置项按钮将对象设置到本地存储,并获取该项以从本地存储中获取键值对。
Users can click the set item button to set the object into the local storage and get the item button to get the key-value pair from the local storage.
<html>
<body>
<button onclick = "setItem()"> Set Item </button>
<button onclick = "getItem()"> Get Item </button>
<p id = "demo"> </p>
<script>
const output = document.getElementById('demo');
function setItem() {
const animal = {
name: "Lion",
color: "Yellow",
food: "Non-vegetarian",
}
localStorage.setItem("animal", JSON.stringify(animal));
}
function getItem() {
const animal = localStorage.getItem("animal");
output.innerHTML = "The animal object is: " + animal;
}
</script>
</body>
</html>
Example: Removing the items from the local storage
在下面的代码中,当网页加载到浏览器中时,我们在本地存储中设置“name”和“john”键值对。
In the below code, we set the 'name' and 'john' key-value pair in the local storage when the web page loads into the browser.
然后,用户可以单击获取项按钮从本地存储中获取该项。它将向您显示名称。
After that, users can click the get item button to get the item from local storage. It will show you the name.
在单击移除项按钮后,您可以再次单击获取项按钮,它将向您显示 null,因为该项已从本地存储中删除。
You can click the get item button again after clicking the remove item button, and it will show you null as the item got deleted from the local storage.
<html>
<body>
<button onclick = "getItem()"> Get Item </button>
<button onclick = "removeItem()"> Remvoe Item </button>
<p id = "demo"></p>
<script>
const output = document.getElementById('demo');
localStorage.setItem('name', 'John');
function getItem() {
output.innerHTML = "The name of the person is: " +
localStorage.getItem('name');
}
function removeItem() {
localStorage.removeItem('name');
output.innerHTML = 'Name removed from local storage. Now, you can\'t get it.';
}
</script>
</body>
</html>
The Window sessionStorage Object
sessionStorage 对象还允许以键值对格式在浏览器中存储数据。
The sessionStorage object also allows storing the data in the browser in the key-value pair format.
它还允许您存储多达 5 MB 的数据。
It also allows you to store the data up to 5 MB.
当您关闭浏览器的选项卡时,存储在会话存储中的数据将过期。这是会话存储和本地存储之间的主要区别。您还可以使用 removeItem() 或 clear() 方法从会话存储中移除该项,而无需关闭浏览器的选项卡。
The data stored in the session storage expires when you close the tab of the browsers. This is the main difference between the session storage and local storage. You can also use the removeItem() or clear() method to remove the items from the session storage without closing the browser’s tab.
注意 – 某些浏览器(如 Chrome 和 Firefox)会在您在关闭浏览器选项卡后重新打开它时维护会话存储数据。如果您关闭浏览器窗口,它肯定会删除会话存储数据。
Note – Some browsers like Chrome and Firefox maintain the session storage data if you re-open the browser’s tab after closing it. If you close the browser window, it will definitely delete the session storage data.
Syntax
请遵循以下语法,使用会话存储对象设置和获取会话存储中的数据。
Follow the syntax below to use the session storage object to set and get data from the session storage.
sessionStorage.setItem(key, value); // To set key-value pair
sessionStorage.getItem(key); // To get data using a key
setItem() 和 getItem() 方法在使用 localStorage 对象时与 sessionStorage 对象具有相同的结果。
The setItem() and getItem() methods give the same result with the sessionStorage object as the localStorage object.
Parameters
-
key − It is a key in the string format.
-
value − It is a value for the key in the string format.
Example
在以下代码中,我们将“username”用作键,“tutorialspoint”用作值。我们使用 setItem() 方法将键值对存储在 sessionStorage 对象中。
In the below code, we used the 'username' as a key and 'tutorialspoint' as a value. We store the key-value pair in the sessionStorage object using the setItem() method.
单击设置项目按钮后,您可以单击获取项目按钮以从会话存储中获取键值对。
You can click the get item button after clicking the set item button to get the key-value pair from the session storage.
<html>
<body>
<button onclick = "setItem()"> Set Item </button>
<button onclick = "getItem()"> Get Item </button>
<p id = "output"> </p>
<script>
const output = document.getElementById('output');
function setItem() {
sessionStorage.setItem("username", "tutorialspoint");
}
function getItem() {
const username = sessionStorage.getItem("username");
output.innerHTML = "The user name is: " + username;
}
</script>
</body>
</html>
不能将文件或图像数据直接存储在本地存储或会话存储中,但可以读取文件数据,将其转换为字符串,并将其存储在会话存储中。
You can’t store the file or image data directly in the local or session storage, but you can read the file data, convert it into the string, and store it in the session storage.
Example
在以下代码中,我们使用 <input> 元素从用户获取图像输入。当用户上传图像时,它将调用 handleImageUpload() 函数。
In the below code, we have used the <input> element to take the image input from users. When a user uploads the image, it will call the handleImageUpload() function.
在 handleImageUpload() 函数中,我们获取上传的图像。之后,我们使用 FileReader 读取图像数据,并将其设置到会话存储中。
In the handleImageUpload() function, we get the uploaded image. After that, we read the image data using the FileReader and set the data into the session storage.
在 getImage() 函数中,我们从会话存储中获取图像,并将其数据设置为图像的“src”属性的值。
In the getImage() function, we get the image from the session storage and set its data as a value of the 'src' attribute of the image.
用户可以先上传图像,再单击“获取图像”按钮,以在网页上显示图像。
Users can upload the image first and click the get Image button to display the image on the web page.
<html>
<body>
<h2> Upload image of size less than 5 MB </h2>
<input type = "file" id = "image" accept = "image/*" onchange = "handleImageUpload()">
<div id = "output"> </div> <br>
<button onclick = "getImage()"> Get Image </button>
<script>
// To handle image upload
function handleImageUpload() {
const image = document.getElementById('image');
const output = document.getElementById('output');
const file = image.files[0];
// Read Image file
if (file) {
const reader = new FileReader();
reader.onload = function (event) {
const data = event.target.result;
// Storing the image data in sessionStorage
sessionStorage.setItem('image', data);
};
reader.readAsDataURL(file);
}
}
// Function to get image
function getImage() {
let data = sessionStorage.getItem("image");
output.innerHTML = `<img src="${data}" alt="Uploaded Image" width="300">`;
}
</script>
</body>
</html>
您还可以像使用 localStorage 一样使用 removeItem() 或 clear() 方法以及 sessionStorage 对象。
You can also use the removeItem() or clear() method with the sessionStorage object like the localStorage.
Cookie Vs localStorage Vs sessionStorage
在这里,我们给出了 cookie、localStorage 和 sessionStorage 对象之间的差异。
Here, we have given the difference between the cookie, localStorage, and sessionStorage objects.
Feature |
Cookie |
Local storage |
Session storage |
Storage Limit |
4 KB per cookie |
5 MB |
5 MB |
Expiry |
It has an expiry date. |
It never expires. |
It gets deleted when you close the browser window. |
Accessibility |
It can be accessed on both the client and server. |
It can be accessed by the client only. |
It can be accessed by the client only. |
Security |
It can be vulnerable. |
It is fully secured. |
It is fully secured. |
Storage Object Properties and Methods
Property/Method |
Description |
key(n) |
To get the name of the nth key from the local or session storage. |
length |
To get the count of key-value pairs in the local or session storage. |
getItem(key) |
To get a value related to the key passed as an argument. |
setItem(key, value) |
To set or update key-value pair in the local or session storage. |
removeItem(key) |
To remove key-value pairs from the storage using its key. |
clear() |
To remove all key-value pairs from the local or session storage. |