JavaScript - Storage API
什么是 Web Storage API?
JavaScript 中的 Web Storage API 允许我们在用户的本地系统或硬盘中存储数据。在 Storage API 引入 JavaScript 之前,cookies 被用来在用户的浏览器中存储数据。
cookies 的主要问题是,每当浏览器请求数据时,服务器必须发送它并将其存储在浏览器中。有时,攻击者也可能攻击并窃取这些数据。
使用 Storage API 的情况下,我们可以将用户数据存储在浏览器中,这些数据仅限于用户的设备。
JavaScript 包含两个不同的对象,用于在本地存储数据。
localStorage
sessionStorage
在这里,我们解释了 localStorage 和 sessionStorage。
Window localStorage 对象
localStorage 对象允许您以键值对格式在用户的浏览器中本地存储数据。
您可以在 local storage 中存储最多 5 MB 的数据。
无论您在 local storage 中存储什么数据,它都不会过期。不过,您可以使用 removeItem() 方法删除特定项,或使用 clear() 删除 local storage 中的所有项。
语法
我们可以使用以下语法从浏览器的 local storage 中设置和获取项。
localStorage.setItem(key, value); // 设置键值对 localStorage.getItem(key); // 使用键获取数据
在上述语法中,setItem() 方法在 local storage 中设置项,而 getItem() 方法使用其键从 local storage 中获取项。
参数
key − 可以是任何字符串。
value − 是字符串格式的值。
示例
在下面的代码中,我们在 setItem() 函数内部将 'fruit' 设置为键,将 'Apple' 设置为值,并存储到 local storage 中。当用户点击按钮时调用 setItem() 函数。
在 getItem() 函数中,我们从 local storage 中获取 'fruit' 键的值。
用户可以先点击 set item 按钮,然后点击 get item 按钮,从 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() 方法将对象转换为字符串并存储到 local storage 中。
示例:在 local storage 中存储对象
在下面的代码中,我们创建了 animal 对象。然后,使用 JSON.stringify() 方法将其转换为字符串,并将其作为 'animal' 键的值存储。
用户可以点击 set item 按钮将对象设置到 local storage 中,并点击 get item 按钮从 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>
示例:从 local storage 中删除项
在下面的代码中,当网页加载到浏览器中时,我们在 local storage 中设置了 'name' 和 'john' 键值对。
之后,用户可以点击 get item 按钮从 local storage 中获取项。它将显示 name。
点击 remove item 按钮后再次点击 get item 按钮,它将显示 null,因为该项已从 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>
Window sessionStorage 对象
sessionStorage 对象也允许以键值对格式在浏览器中存储数据。
它允许存储的数据上限为 5 MB。
会话存储中的数据在关闭浏览器标签页时过期。这是 session storage 和 local storage 的主要区别。您也可以使用 removeItem() 或 clear() 方法在不关闭浏览器标签页的情况下从会话存储中移除项目。
注意 某些浏览器如 Chrome 和 Firefox 在关闭标签页后重新打开时会保留 session storage 数据。如果关闭浏览器窗口,则一定会删除 session storage 数据。
语法
按照以下语法使用 session storage 对象来设置和获取会话存储中的数据。
sessionStorage.setItem(key, value); // 设置键值对 sessionStorage.getItem(key); // 使用键获取数据
setItem() 和 getItem() 方法在使用 sessionStorage 对象时与 localStorage 对象产生相同的结果。
参数
key − 它是字符串格式的键。
value − 它是字符串格式的键值。
示例
在下面的代码中,我们使用 'username' 作为键,'' 作为值。我们使用 setItem() 方法将键值对存储到 sessionStorage 对象中。
您可以在点击 set item 按钮后点击 get item 按钮来从会话存储中获取键值对。
<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", "");
}
function getItem() {
const username = sessionStorage.getItem("username");
output.innerHTML = "The user name is: " + username;
}
</script>
</body>
</html>
您不能直接在 local 或 session storage 中存储文件或图像数据,但您可以读取文件数据,将其转换为字符串,并存储到 session storage 中。
示例
在下面的代码中,我们使用了 <input> 元素从用户处获取图像输入。当用户上传图像时,将调用 handleImageUpload() 函数。
在 handleImageUpload() 函数中,我们获取上传的图像。然后,我们使用 FileReader 读取图像数据,并将数据设置到 session storage 中。
在 getImage() 函数中,我们从 session storage 获取图像,并将其数据设置为图像的 'src' 属性的值。
用户可以先上传图像,然后点击 get Image 按钮在网页上显示图像。
<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>
// 处理图像上传
function handleImageUpload() {
const image = document.getElementById('image');
const output = document.getElementById('output');
const file = image.files[0];
// 读取图像文件
if (file) {
const reader = new FileReader();
reader.onload = function (event) {
const data = event.target.result;
// 将图像数据存储到 sessionStorage 中
sessionStorage.setItem('image', data);
};
reader.readAsDataURL(file);
}
}
// 获取图像的函数
function getImage() {
let data = sessionStorage.getItem("image");
output.innerHTML = `<img src="${data}" alt="Uploaded Image" width="300">`;
}
</script>
</body>
</html>
您也可以像使用 localStorage 一样,在 sessionStorage 对象上使用 removeItem() 或 clear() 方法。
Cookie 与 localStorage 与 sessionStorage 的对比
这里,我们列出了 cookie、localStorage 和 sessionStorage 对象之间的区别。
| 特性 | Cookie | Local storage | Session storage |
|---|---|---|---|
| 存储限制 | 每个 cookie 4 KB | 5 MB | 5 MB |
| 过期时间 | 具有过期日期。 | 永不过期。 | 关闭浏览器窗口时会被删除。 |
| 可访问性 | 可在客户端和服务器端访问。 | 仅可由客户端访问。 | 仅可由客户端访问。 |
| 安全性 | 可能存在安全漏洞。 | 完全安全。 | 完全安全。 |
Storage 对象属性和方法
| 属性/方法 | 描述 |
|---|---|
| key(n) | 获取 local 或 session storage 中第 n 个 key 的名称。 |
| length | 获取 local 或 session storage 中键值对的数量。 |
| getItem(key) | 获取作为参数传入的 key 对应的值。 |
| setItem(key, value) | 在 local 或 session storage 中设置或更新键值对。 |
| removeItem(key) | 使用 key 从 storage 中移除键值对。 |
| clear() | 从 local 或 session storage 中移除所有键值对。 |