在现代 Web 应用中,跨标签页通信的需求越来越普遍。无论是实现多标签页之间的数据同步,还是构建实时协作功能,跨标签页通信都能极大地提升用户体验。今天,我们将探讨一种基于 IndexedDB 的跨标签页通信方案。IndexedDB 是一种在客户端存储大量结构化数据的底层 API,它不仅支持持久化存储,还可以通过事务机制实现跨标签页的数据同步。
一、什么是 IndexedDB?
IndexedDB 是一种在客户端存储大量结构化数据的底层 API。它支持事务、索引和异步操作,适用于需要存储大量数据的场景。IndexedDB 的主要特点包括:
- 持久化存储:数据存储在浏览器的本地存储中,即使浏览器关闭后数据也不会丢失。
- 事务支持:支持事务操作,确保数据的一致性和完整性。
- 索引功能:通过索引可以高效地查询数据。
- 异步操作:所有操作都是异步的,不会阻塞主线程。
适用场景
- 数据同步:在多个标签页之间同步数据,如用户状态、实时消息等。
- 离线支持:在离线状态下存储数据,待网络恢复后同步到服务器。
- 性能优化:减少重复的网络请求,通过本地存储提升性能。
二、IndexedDB 实现跨标签页通信
(一)基本操作
在实现跨标签页通信之前,我们需要了解 IndexedDB 的基本操作,包括打开数据库、添加数据、查询数据等。
1. 打开数据库
function openDB(dbName, version = 1) {return new Promise((resolve, reject) => {const request = indexedDB.open(dbName, version);request.onsuccess = function (event) {resolve(event.target.result);};request.onerror = function (event) {reject(event.target.error);};request.onupgradeneeded = function (event) {const db = event.target.result;if (!db.objectStoreNames.contains("stu")) {db.createObjectStore("stu", { keyPath: "stuId", autoIncrement: true });}};});
}
2. 添加数据
function addData(db, storeName, data) {const transaction = db.transaction([storeName], "readwrite");const objectStore = transaction.objectStore(storeName);const request = objectStore.add(data);request.onsuccess = function () {console.log("数据写入成功");};request.onerror = function (event) {console.error("数据写入失败", event.target.error);};
}
3. 查询数据
function getDataByKey(db, storeName) {return new Promise((resolve, reject) => {const transaction = db.transaction([storeName], "readonly");const objectStore = transaction.objectStore(storeName);const request = objectStore.getAll();request.onsuccess = function (event) {resolve(event.target.result);};request.onerror = function (event) {reject(event.target.error);};});
}
(二)跨标签页通信实现
通过定时器轮询的方式,我们可以实现跨标签页的通信。每个标签页定期查询 IndexedDB 中的数据,如果有更新,则进行相应的处理。
页面一:添加数据
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>页面一</title>
</head>
<body>新增学生<div><span>学生学号:</span><input type="text" name="stuId" id="stuId"></div><div><span>学生姓名:</span><input type="text" name="stuName" id="stuName"></div><div><span>学生年龄:</span><input type="text" name="stuAge" id="stuAge"></div><button id="addBtn">新增学生</button><script src="./db.js"></script><script>const addBtn = document.querySelector("#addBtn");const stuId = document.querySelector("#stuId");const stuName = document.querySelector("#stuName");const stuAge = document.querySelector("#stuAge");openDB("stuDB", 1).then((db) => {addBtn.onclick = function () {addData(db, "stu", {stuId: stuId.value,stuName: stuName.value,stuAge: stuAge.value});stuId.value = stuName.value = stuAge.value = "";};});</script>
</body>
</html>
页面二:查询并显示数据
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>页面二</title><style>table {border: 1px solid;border-collapse: collapse;}table td {border: 1px solid;}</style>
</head>
<body>学生表<table id="tab"><tr><td>学号</td><td>姓名</td><td>年龄</td></tr></table><script src="./db.js"></script><script>function render(arr) {const tab = document.querySelector("#tab");let str = arr.map((item) => {return `<tr><td>${item.stuId}</td><td>${item.stuName}</td><td>${item.stuAge}</td></tr>`;}).join("");tab.innerHTML += str;}async function renderTable() {const db = await openDB("stuDB", 1);let stuInfo = await getDataByKey(db, "stu");render(stuInfo);setInterval(async () => {const stuInfo2 = await getDataByKey(db, "stu");if (stuInfo2.length !== stuInfo.length) {stuInfo = stuInfo2;render(stuInfo);}}, 1000);}renderTable();</script>
</body>
</html>
(三)效果
- 打开两个标签页,分别加载页面一和页面二。
- 在页面一中输入学生信息并点击“新增学生”按钮。
- 页面二会定期查询 IndexedDB 中的数据,并在表格中显示最新的学生信息。
三、注意事项
(一)同源限制
IndexedDB 只能在同源页面之间使用。如果页面的协议、域名或端口不同,通信将无法进行。
(二)浏览器支持
虽然现代浏览器(如 Chrome、Firefox、Safari)都支持 IndexedDB,但在使用前最好进行兼容性检查。
if (!window.indexedDB) {console.warn("IndexedDB 不被支持");
}
(三)性能影响
虽然 IndexedDB 的性能开销较小,但在高频率读写数据时,仍需注意对性能的影响。