/** * OfferPie 跨标签页通信桥接组件 * 用于浏览器插件与网站页面之间的纯本地通信(不依赖任何后端接口) * * 【使用说明】 * 1. 引入并创建实例: * import { createChannelBridge } from './channelBridge' * const bridge = createChannelBridge({ domain: 'offerpai.com', isPlugin: true }) * * 2. 发送数据(单次,同时写缓存 + 广播): * bridge.put('offerpai.com', 'resumeStatus', { ... }) * * 3. 高频发送(节流写缓存,每次都广播): * bridge.emit('offerpai.com', 'cursorPosition', { ... }) * * 4. 主动获取一次数据(先广播问对方,60ms超时转IndexedDB): * const result = await bridge.get('offerpai.com', 'resumeStatus') * * 5. 持续监听数据变化(初始读一次缓存,后续实时接收 put/emit): * const unwatch = bridge.watch('offerpai.com', 'resumeStatus', (data) => { ... }) * // 取消监听 * unwatch() * * 6. 销毁实例(页面卸载时调用): * bridge.destroy() * * 【参数说明】 * - domain: 频道域名标识,不同网站项目用不同域名隔离 * - isPlugin: 是否为插件环境,默认 false(非插件时会启用 Web Lock 保活) * * 【数据类型要求】 * - 传递的数据必须有 TypeScript 类型定义(泛型约束 extends object) * - 组件自动为每条数据添加 createTime 和 updateTime 字段 * * ============================================================ * 【通信数据名称注册表】 * 在此区域记录所有通信数据的名称、类型和用途说明 * 新增数据时在此补充,删除时移除对应行 * ------------------------------------------------------------ * | 数据名(name) | 中文名称 | 说明 | * | ----------------------------- | -------------- | --------------------------------- | * | offerpieBrowserPlugUsage | 插件使用状态 | 标识插件正在运行 { usage: string } | * ============================================================ */ // ============ 类型定义 ============ /** 组件自动附加的时间戳字段 */ export interface BridgeTimestamp { /** 数据首次创建时间(格式:yyyy-MM-dd HH:mm:ss) */ createTime: string /** 数据最近更新时间(格式:yyyy-MM-dd HH:mm:ss) */ updateTime: string } /** 带时间戳的完整数据包装 */ export type BridgeData = T & BridgeTimestamp /** IndexedDB 存储记录结构 */ interface DBRecord { /** 数据名称(唯一索引) */ name: string /** JSON 数据本体 */ data: object /** 创建时间 */ createTime: string /** 更新时间 */ updateTime: string } /** BroadcastChannel 消息结构 */ interface ChannelMessage { /** 消息类型 */ type: 'put' | 'emit' | 'get-request' | 'get-response' /** 数据名称 */ name: string /** 请求唯一ID(用于 get 请求-响应匹配) */ id?: string /** 数据本体(put/emit/get-response 携带) */ data?: object /** 创建时间 */ createTime?: string /** 更新时间 */ updateTime?: string } /** watch 回调函数类型 */ type WatchCallback = (data: BridgeData | null) => void /** 创建实例的配置参数 */ export interface ChannelBridgeOptions { /** 默认域名(可在方法调用时覆盖) */ domain: string /** 是否为插件环境,默认 false。非插件时启用 Web Lock 保活 */ isPlugin?: boolean } // ============ 常量 ============ /** IndexedDB 数据库名称(含固定雪花ID保证唯一性) */ const DB_NAME = 'offerpie_comm_7394028156183472' /** IndexedDB 版本号 */ const DB_VERSION = 1 /** get 方法 BroadcastChannel 超时时间(毫秒) */ const GET_TIMEOUT_MS = 60 /** emit 方法节流写库间隔(毫秒) */ const EMIT_THROTTLE_MS = 500 // ============ 工具函数 ============ /** 获取当前时间的 localDateTime 格式字符串:yyyy-MM-dd HH:mm:ss */ function nowLocalDateTime(): string { const d = new Date() const pad = (n: number) => String(n).padStart(2, '0') return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}` } /** 生成简单唯一ID(用于 get 请求匹配) */ function uid(): string { return Date.now().toString(36) + Math.random().toString(36).slice(2, 8) } // ============ IndexedDB 操作 ============ /** 打开/创建 IndexedDB 数据库,按 domain 动态创建 ObjectStore */ function openDB(storeName: string): Promise { return new Promise((resolve, reject) => { const request = indexedDB.open(DB_NAME, DB_VERSION) request.onupgradeneeded = () => { const db = request.result if (!db.objectStoreNames.contains(storeName)) { const store = db.createObjectStore(storeName, { keyPath: 'name' }) store.createIndex('name', 'name', { unique: true }) } } request.onsuccess = () => { const db = request.result // 如果 store 不存在(版本没升级的情况),关闭后升版本重建 if (!db.objectStoreNames.contains(storeName)) { db.close() const version = db.version + 1 const req2 = indexedDB.open(DB_NAME, version) req2.onupgradeneeded = () => { const db2 = req2.result if (!db2.objectStoreNames.contains(storeName)) { const store = db2.createObjectStore(storeName, { keyPath: 'name' }) store.createIndex('name', 'name', { unique: true }) } } req2.onsuccess = () => resolve(req2.result) req2.onerror = () => reject(req2.error) } else { resolve(db) } } request.onerror = () => reject(request.error) }) } /** 写入或更新一条记录到 IndexedDB */ async function dbPut(storeName: string, record: DBRecord): Promise { const db = await openDB(storeName) return new Promise((resolve, reject) => { const tx = db.transaction(storeName, 'readwrite') const store = tx.objectStore(storeName) store.put(record) tx.oncomplete = () => { db.close(); resolve() } tx.onerror = () => { db.close(); reject(tx.error) } }) } /** 从 IndexedDB 读取一条记录 */ async function dbGet(storeName: string, name: string): Promise { const db = await openDB(storeName) return new Promise((resolve, reject) => { const tx = db.transaction(storeName, 'readonly') const store = tx.objectStore(storeName) const req = store.get(name) req.onsuccess = () => { db.close(); resolve(req.result || null) } req.onerror = () => { db.close(); reject(req.error) } }) } // ============ 核心:创建通信桥接实例 ============ export function createChannelBridge(options: ChannelBridgeOptions) { const { domain, isPlugin = false } = options /** BroadcastChannel 实例缓存(按 domain 隔离频道) */ const channels = new Map() /** watch 订阅回调注册表:key = `${domain}::${name}` */ const watchers = new Map>>() /** emit 节流定时器:key = `${domain}::${name}` */ const emitTimers = new Map>() /** emit 节流暂存最新数据:key = `${domain}::${name}` */ const emitPending = new Map() /** get 请求等待队列:key = requestId */ const getResolvers = new Map | null) => void>() // --- Web Lock 保活(非插件环境) --- if (!isPlugin && typeof navigator !== 'undefined' && navigator.locks) { navigator.locks.request('offerpie-keep-alive', () => new Promise(() => {})) } /** 获取或创建指定 domain 的 BroadcastChannel */ function getChannel(channelDomain: string): BroadcastChannel { if (channels.has(channelDomain)) return channels.get(channelDomain)! const ch = new BroadcastChannel(`offerpie-bridge-${channelDomain}`) ch.onmessage = (event: MessageEvent) => handleMessage(channelDomain, event.data) channels.set(channelDomain, ch) return ch } /** 处理收到的 BroadcastChannel 消息 */ async function handleMessage(channelDomain: string, msg: ChannelMessage) { const watchKey = `${channelDomain}::${msg.name}` if (msg.type === 'put' || msg.type === 'emit') { // 收到对方的数据推送,触发本地 watch 回调 const wrapped = msg.data && msg.createTime && msg.updateTime ? { ...msg.data, createTime: msg.createTime, updateTime: msg.updateTime } as BridgeData : null const callbacks = watchers.get(watchKey) if (callbacks) { callbacks.forEach(cb => cb(wrapped)) } } if (msg.type === 'get-request' && msg.id) { // 收到对方的 get 请求,从本地 IndexedDB 读取数据并回复 const record = await dbGet(channelDomain, msg.name) const ch = getChannel(channelDomain) const response: ChannelMessage = { type: 'get-response', name: msg.name, id: msg.id, data: record?.data, createTime: record?.createTime, updateTime: record?.updateTime, } ch.postMessage(response) } if (msg.type === 'get-response' && msg.id) { // 收到对方对 get 请求的回复 const resolver = getResolvers.get(msg.id) if (resolver) { getResolvers.delete(msg.id) if (msg.data && msg.createTime && msg.updateTime) { resolver({ ...msg.data, createTime: msg.createTime, updateTime: msg.updateTime } as BridgeData) } else { resolver(null) } } } } // 初始化默认频道监听 getChannel(domain) // --- 公开方法 --- /** * put - 单次发送数据(写入 IndexedDB + BroadcastChannel 广播) * @param targetDomain 目标域名频道 * @param name 数据名称 * @param data 数据本体(需有 TS 类型定义) */ async function put(targetDomain: string, name: string, data: T): Promise { const now = nowLocalDateTime() // 读取已有记录判断是否为新建 const existing = await dbGet(targetDomain, name) const createTime = existing?.createTime || now const updateTime = now const record: DBRecord = { name, data, createTime, updateTime } // 写入 IndexedDB await dbPut(targetDomain, record) // BroadcastChannel 广播 const ch = getChannel(targetDomain) const msg: ChannelMessage = { type: 'put', name, data, createTime, updateTime } ch.postMessage(msg) } /** * emit - 高频发送数据(每次都广播,节流 500ms 写一次 IndexedDB) * @param targetDomain 目标域名频道 * @param name 数据名称 * @param data 数据本体(需有 TS 类型定义) */ async function emit(targetDomain: string, name: string, data: T): Promise { const now = nowLocalDateTime() const key = `${targetDomain}::${name}` // 先尝试获取 createTime(从暂存或数据库) let createTime: string const pending = emitPending.get(key) if (pending) { createTime = pending.createTime } else { const existing = await dbGet(targetDomain, name) createTime = existing?.createTime || now } const updateTime = now const record: DBRecord = { name, data, createTime, updateTime } // 暂存最新数据 emitPending.set(key, record) // BroadcastChannel 每次都广播(保证 watch 实时性) const ch = getChannel(targetDomain) const msg: ChannelMessage = { type: 'emit', name, data, createTime, updateTime } ch.postMessage(msg) // 节流写库 if (!emitTimers.has(key)) { emitTimers.set(key, setTimeout(async () => { emitTimers.delete(key) const latestRecord = emitPending.get(key) if (latestRecord) { emitPending.delete(key) await dbPut(targetDomain, latestRecord) } }, EMIT_THROTTLE_MS)) } } /** * get - 主动获取一次数据(先 BroadcastChannel 请求,60ms 超时转 IndexedDB) * @param targetDomain 目标域名频道 * @param name 数据名称 * @returns 数据本体(含 createTime/updateTime),无数据返回 null */ async function get(targetDomain: string, name: string): Promise | null> { const ch = getChannel(targetDomain) const requestId = uid() // 发起广播请求 const msg: ChannelMessage = { type: 'get-request', name, id: requestId } ch.postMessage(msg) // 等待响应或超时 const result = await new Promise | null>((resolve) => { getResolvers.set(requestId, resolve as any) setTimeout(() => { if (getResolvers.has(requestId)) { getResolvers.delete(requestId) resolve(null) // 超时,标记为未收到响应 } }, GET_TIMEOUT_MS) }) // 如果广播拿到了数据直接返回 if (result) return result // 超时降级读 IndexedDB const record = await dbGet(targetDomain, name) if (record) { return { ...record.data, createTime: record.createTime, updateTime: record.updateTime } as BridgeData } return null } /** * watch - 持续监听数据变化(初始读一次缓存,后续实时接收 put/emit 推送) * @param targetDomain 目标域名频道 * @param name 数据名称 * @param callback 数据变化回调,参数为最新数据或 null * @returns 取消监听的函数 */ function watch(targetDomain: string, name: string, callback: WatchCallback): () => void { const key = `${targetDomain}::${name}` // 确保频道已初始化 getChannel(targetDomain) // 注册回调 if (!watchers.has(key)) watchers.set(key, new Set()) watchers.get(key)!.add(callback) // 初始读取 IndexedDB dbGet(targetDomain, name).then((record) => { if (record) { callback({ ...record.data, createTime: record.createTime, updateTime: record.updateTime } as BridgeData) } else { callback(null) } }) // 返回取消监听函数 return () => { const set = watchers.get(key) if (set) { set.delete(callback) if (set.size === 0) watchers.delete(key) } } } /** * destroy - 销毁实例,关闭所有频道,清除定时器 */ function destroy(): void { channels.forEach(ch => ch.close()) channels.clear() watchers.clear() emitTimers.forEach(timer => clearTimeout(timer)) emitTimers.clear() emitPending.clear() getResolvers.clear() } return { put, emit, get, watch, destroy } }