banner
NEWS LETTER

前端使用浏览器的本地存储功能来保存网页数据到本地

Scroll down

前端使用浏览器的本地存储功能来保存网页数据到本地。

下面是一些可用的方法:

1、使用 localStorage 或 sessionStorage API 将数据保存在浏览器的缓存中。这种方式只能保存较小量的数据,通常用于缓存一些用户偏好设置、表单数据等

1
2
3
4
5
6
7
8
// 保存数据到 localStorage
localStorage.setItem("key", "value");

// 获取 localStorage 中的数据
const data = localStorage.getItem("key");

// 删除 localStorage 中的数据
localStorage.removeItem("key");

2、使用 Web Storage API 将数据保存在浏览器的文件系统中。这种方式可以保存更大量的数据,并且具有更好的安全性和可靠性,但需要获取用户权限才能使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 请求用户授权
navigator.storage.requestPersistent().then((granted) => {
if (granted) {
// 保存数据到文件系统中
window.caches.open("data").then((cache) => {
cache.put("/", new Response("data"));
});
}
});

// 获取保存在文件系统中的数据
window.caches
.match("/")
.then((response) => {
return response.text();
})
.then((data) => {
console.log(data);
});

3、使用 File System Access API 将数据保存为本地文件。这种方式可以保存任意类型和大小的数据,并且用户不需要手动选择文件保存位置,但仅在最新版本的 Chrome 浏览器中可用。

1
2
3
4
5
6
7
8
9
10
11
// 请求用户授权
const fileHandle = await window.showSaveFilePicker();

// 创建文件写入流
const writableStream = await fileHandle.createWritable();

// 将数据写入文件
await writableStream.write("data");

// 关闭文件写入流
await writableStream.close();
其他文章
请输入关键词进行搜索