multi-tab-sync
v1.0.0
Published
A powerful multi-tab data synchronization library for Vue.js and browser extensions
Maintainers
Readme
Multi-Tab Sync
https://img.shields.io/npm/v/multi-tab-sync.svg https://img.shields.io/badge/License-MIT-yellow.svg https://img.shields.io/badge/Vue-2%2520%2526%25203-brightgreen.svg https://img.shields.io/bundlephobia/minzip/multi-tab-sync
一个强大的多标签页数据同步库,专为Vue.js和浏览器扩展开发设计。支持跨标签页实时数据同步,提供优雅的API和灵活的配置选项。
✨ 特性
- 🚀 多策略支持:BroadcastChannel、localStorage事件、Chrome扩展API
- 🎯 Vue友好:完美支持Vue 2和Vue 3,提供插件和mixin两种使用方式
- 🔧 浏览器扩展优化:专为Chrome/Firefox扩展开发设计
- 📦 轻量高效:核心代码<5KB,零依赖
- 🛡 类型安全:完整的TypeScript类型定义
- ⚡ 实时同步:毫秒级数据同步响应
- 🔒 数据安全:支持数据序列化自定义和过期时间设置
- 📱 兼容性强:支持现代浏览器和旧版浏览器降级方案
📦 安装
bash
# npm
npm install multi-tab-sync
# yarn
yarn add multi-tab-sync
# pnpm
pnpm add multi-tab-sync🚀 快速开始
在Vue项目中使用
javascript
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import { MultiTabSyncPlugin } from 'multi-tab-sync'
const app = createApp(App)
app.use(MultiTabSyncPlugin, {
prefix: 'myapp_',
useBroadcastChannel: true
})
app.mount('#app')vue
<!-- MyComponent.vue -->
<template>
<div>
<h2>用户设置</h2>
<input v-model="theme" placeholder="主题设置">
<button @click="saveSettings">保存设置</button>
</div>
</template>
<script>
export default {
inject: ['multiTabSync'],
data() {
return {
theme: 'light',
userPreferences: {}
}
},
mounted() {
// 加载其他标签页的设置
const savedTheme = this.multiTabSync.get('theme')
if (savedTheme) {
this.theme = savedTheme
}
// 监听设置变化
this.multiTabSync.on((message) => {
if (message.type === 'SET' && message.key === 'theme') {
this.theme = message.value
console.log('主题已从其他标签页更新:', this.theme)
}
})
},
methods: {
saveSettings() {
this.multiTabSync.set('theme', this.theme, {
expiry: 24 * 60 * 60 * 1000 // 24小时后过期
})
}
}
}
</script>使用Mixin方式(推荐)
vue
<template>
<div :class="[theme, layout]">
<h1>我的应用</h1>
<select v-model="theme">
<option value="light">浅色主题</option>
<option value="dark">深色主题</option>
</select>
</div>
</template>
<script>
export default {
// 自动同步这些数据字段
multiTabSync: ['theme', 'layout', 'userPreferences'],
data() {
return {
theme: 'light',
layout: 'grid',
userPreferences: {
fontSize: 14,
language: 'zh-CN'
}
}
},
mounted() {
console.log('数据已自动跨标签页同步')
}
}
</script>在浏览器扩展中使用
javascript
// background.js (后台脚本)
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message?.source === 'multi-tab-sync') {
// 广播到所有标签页
chrome.tabs.query({}, (tabs) => {
tabs.forEach((tab) => {
chrome.tabs.sendMessage(tab.id, message)
})
})
}
})
// popup.js (弹出页面)
import SyncManager from 'multi-tab-sync'
const syncManager = new SyncManager({
useChromeExtension: true,
prefix: 'extension_'
})
// 保存扩展设置
syncManager.set('apiKey', 'your-secret-key')
syncManager.set('options', {
darkMode: true,
notifications: false
})
// 监听设置变化
syncManager.on((message) => {
if (message.type === 'SET') {
console.log('扩展设置已更新:', message)
}
})⚙️ 配置选项
javascript
const options = {
// 存储键名前缀,避免冲突
prefix: 'mts_',
// 是否使用BroadcastChannel(现代浏览器)
useBroadcastChannel: true,
// 是否使用localStorage(兼容旧浏览器)
useLocalStorage: true,
// 是否使用Chrome扩展API
useChromeExtension: false,
// 自定义序列化方法
serialization: {
serialize: JSON.stringify,
deserialize: JSON.parse
},
// 错误处理回调
onError: (error) => {
console.error('同步错误:', error)
},
// 调试模式
debug: process.env.NODE_ENV !== 'production'
}
app.use(MultiTabSyncPlugin, options)📖 API参考
SyncManager实例方法
| 方法 | 描述 | 示例 |
| -------------------------- | ------------ | ------------------------------------------- |
| set(key, value, options) | 设置数据 | set('theme', 'dark', { expiry: 3600000 }) |
| get(key) | 获取数据 | get('theme') → 'dark' |
| remove(key) | 删除数据 | remove('theme') |
| clear() | 清空所有数据 | clear() |
| getAll() | 获取所有数据 | getAll() → { theme: 'dark' } |
| on(callback) | 监听数据变化 | on((msg) => console.log(msg)) |
| off(callback) | 移除监听器 | off(callback) |
消息格式
javascript
{
type: 'SET' | 'REMOVE' | 'CLEAR', // 操作类型
key: 'mts_theme', // 存储键名
value: 'dark', // 数据值(SET操作)
timestamp: 1627891234567, // 时间戳
expiry: 1627894834567, // 过期时间(可选)
source: 'multi-tab-sync' // 来源标识
}🛠 高级用法
自定义序列化
javascript
import { EncryptionUtil } from './encryption'
app.use(MultiTabSyncPlugin, {
serialization: {
serialize: (data) => {
const json = JSON.stringify(data)
return EncryptionUtil.encrypt(json)
},
deserialize: (encrypted) => {
const json = EncryptionUtil.decrypt(encrypted)
return JSON.parse(json)
}
}
})错误处理
javascript
const syncManager = new SyncManager({
onError: (error) => {
// 发送错误日志
console.error('Sync Error:', error)
// 或者显示用户提示
if (error.message.includes('QuotaExceeded')) {
alert('存储空间不足,请清理一些数据')
}
}
})性能优化
javascript
// 防抖处理频繁更新
let updateTimeout
function debouncedUpdate(key, value) {
clearTimeout(updateTimeout)
updateTimeout = setTimeout(() => {
syncManager.set(key, value)
}, 300)
}🌐 浏览器兼容性
| 特性 | Chrome | Firefox | Safari | Edge | IE | | ---------------- | ------ | ------- | ------ | ---- | -- | | BroadcastChannel | 54+ | 38+ | 15.4+ | 79+ | ❌ | | localStorage | 4+ | 3.5+ | 4+ | 12+ | 8+ | | Chrome扩展API | 支持 | 支持 | ❌ | 支持 | ❌ |
🔧 开发指南
本地开发
bash
# 克隆项目
git clone https://github.com/your-username/multi-tab-sync.git
# 安装依赖
npm install
# 开发模式
npm run dev
# 构建生产版本
npm run build
# 运行测试
npm test贡献代码
- Fork本项目
- 创建特性分支 (
git checkout -b feature/amazing-feature) - 提交更改 (
git commit -m 'Add amazing feature') - 推送到分支 (
git push origin feature/amazing-feature) - 开启Pull Request
📝 更新日志
v1.0.0 (2023-11-01)
- ✅ 初始版本发布
- ✅ 支持Vue 2和Vue 3
- ✅ 多策略同步机制
- ✅ 浏览器扩展支持
- ✅ TypeScript类型定义
🆘 常见问题
Q: 数据在不同域名间能同步吗?
A: 不能,出于安全考虑,数据同步仅限于同源页面。
Q: 如何处理存储空间不足?
A: 库会自动处理QuotaExceeded错误,并通过onError回调通知。
Q: 支持Vue 2吗?
A: 是的,完美支持Vue 2.6+和Vue 3。
Q: 如何调试同步问题?
A: 启用debug模式可以看到详细的日志信息。
📄 许可证
MIT License - 详见 LICENSE 文件。
🤝 支持
如果你觉得这个库有用,请:
- ⭐ 给个Star
- 🐛 提交Issue
- 💡 提出建议
- 🔧 贡献代码
Multi-Tab Sync - 让多标签页数据同步变得简单! 🚀
