96SEO 2026-08-07 19:27 5
在实际项目中。开发者常常会遇到以下痛点:
将 Service Worker与 IndexedDB结合,可以让上述痛点得到根本性解决:离线可用、后台持久任务、低开销的句柄存储还有即时通知。

使用者操作 │ ▼
┌───────────────┐
│ 选择文件夹 │────▶│ 解析视频 │────▶│ 存入IndexedDB │────▶│ 后台自动上传 │────▶│ 发送通知 │
└───────────────┘ └──────────────┘ └────────────────┘ └───────────────────┘ └──────────────┘
│ │ │ │ │ │ │ │ │ │
▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ 全程进度实时反馈程序 │
│ │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────┘
// IdbStore:统一管理 IndexedDB + 内存缓存 + EventBus
/* global IDBKeyRange */
import { useState。useCallback,useEffect } from 'react';import Debug from 'debug';import { openDB } from 'idb';import mitt from 'mitt';按理说,const debug = Debug;说起来,export default class IdbStore {
// 初始化连接、缓存、事件总线
constructor {
this.emitter = mitt;// 事件总线
this.cache = Object.create;// 内存缓存
this.storeName = storeName;this.dbName = dbName;this.dbPromise = openDB(dbName,1。{
upgrade {
const s = db.createObjectStore;s.createIndex;},}),// 启动定时清理过期数据
setTimeout => this.clean,0);}
/** 清理已过期的记录 */
async clean {
const { dbName。storeName,dbPromise,cache } = this;debug,const db = await dbPromise;const keyRangeValue = IDBKeyRange.upperBound);let cursor = await db.transaction
.objectStore
.index
.openCursor;while {
debug;cursor.delete;if {
delete cache;}
cursor = await cursor.continue;}
// 循环执行,保持数据干净
setTimeout => this.clean。60 * 60 * 1000);}
/** React Hook:自动订阅键值变化 */
useStore {
const { emitter } = this;const = useState => this.cache || {});const onChange = useCallback,);useEffect => {
if this.getAsync;emitter.on,return => emitter.off;},),return {
loading:!state ||,!其实,state.dataPromise。data: state.data,};}
/** 写入数据 */
async setData {
const db = await this.dbPromise;话说回来,const info = { key,data };if info.expiredAt = Date.now + expire;this.cache = info;await db.put;debug,this.emitter.emit;}
/** 判断缓存是否仍然有效 */
getNotExpireData {
if return undefined;if ) {
return info.data?,info.dataPromise;}
return undefined;}
/** 异步获取:先查缓存 → DB → fn */
async getAsync {
let info = this.cache;const cacheData = this.getNotExpireData;其实,if return cacheData;info = {},按理说,if info.expiredAt = Date.now + expire;info.dataPromise = this.dbPromise.n(async db => {
debug;info = await db.get;const cached = this.getNotExpireData;if {
this.cache = info;this.emitter.emit;return cached;}
if return undefined;debug,return fn
.n;return data,})
.catch;}),});this.cache = info;return info.dataPromise;其实,}
}
// BatchUploadVideosWorker:后台批量上传 + 通知逻辑
/* global window Notification */
import rest from '@/services/rest';说起来,import { idbStore } from '@/utils/store';import { multiPartUploadToTOS } from '@/services/tos';import { loadVideoSignature } from '@/utils/video';import { formatDate } from '@/filter/date';说起来,import moment from 'moment';import eventBus from 'utils/eventBus';老实说,import { uploadImgByVideoUrl } from '@/utils/common';怎么说呢,import { getHandle } from '@/utils/file';话说回来,// ---------- 辅助函数 ----------
const getFileByName = async fileName => {
try {
const savedHandle = await getHandle;if return null;老实说,const permission = await savedHandle.queryPermission;不过,if return null;let foundFile = null;async function traverse {
for await ) {
if return;按理说,if {
foundFile = await entry.getFile;return,}
if await traverse;}
}
await traverse;return foundFile;} catch { console.error;return null,}
};const getVideoFileInfo = file => new Promise(resolve => {
const url = URL.createObjectURL;const video= document.createElement;老实说,video.preload='metadata';video.onloadedmetadata==>{ URL.revokeObjectURL;resolve({
从width来看,video.videoWidth,height: video.videoHeight。videoSize:file.size,duration:video.duration});},video.onerror==>{ URL.revokeObjectURL;resolve({
至于width,null,height:null。videoSize:file.size,duration:null});},说起来,video.src=url;}),// ---------- 主类 ----------
class BatchUploadVideosWorker{
constructor{
this.registration=null;// ServiceWorkerRegistration 实例
this.timer=null;// 定时器句柄
this.isRunning=false;// 防止重复 start
}
/** 注册 Service Worker */
async register{
if){
console.warn;其实,return false;}
try{
this.registration=await navigator.serviceWorker.register;return true,}catch{
console.error;return false;}
}
/** 显示桌面通知 */
async showNotification{
if{ console.warn;return,}
this.registration.showNotification(title,{
说到body,fileName,icon:'/favicon.ico'。requireInteraction:true,data:{type:'upload_complete',url:'#/admin/MuVideo'}
});
}
/** 检查缓存并发送进度通知 */
async checkAndSendNotifications{
\t\t// 从 IndexedDB 中读取待处理的视频列表
\t\tconst cacheVideoData=await idbStore.getAsync;\t\tif{
\t\t\tstopBatchUploadVideosWorker;\t\t\treturn;\t\t}
\t\tlet completedCount=0。repeatCount=0,failedCount=0;\t\tconst totalCount=cacheVideoData.videoInfos.length;说起来,\t\t// 使用副本避免遍历过程中直接修改原数组导致索引错位
\t\tconst remainingInfos=;for{
const vi=remainingInfos;const {name,fileName,…说起来,rest}=vi;// 解构所需字段
// 文件是否仍然存在?const file=await getFileByName;if{ remainingInfos.splice;continue,}
// 必要字段校验,缺失则直接剔除
if){
remainingInfos.splice;continue,}
try{
const dateStr=formatDate;const {url}=await multiPartUploadToTOS(file,{
startsWith:`video/${dateStr}/`。bucket:'myt-videos',videoServer:'myt-videos.lab.weidiango.com',hasVle:false});\
// 重复校验
const exists=await rest.find.n);if{ repeatCount++;remainingInfos.splice;怎么说呢,continue;}
// 视频元信息 & 封面生成
const meta=await getVideoFileInfo;const sourceUrl=new URL.origin+new URL.pathname+'?x-oss-process=video/snapshot。t_0,f_jpg,m_fast';const coverUrl=await uploadImgByVideoUrl;const signature=await loadVideoSignature;// 保存到后端数据库
await rest.save('MuVideo',{
url,signature,name,seq:Number,editMonth:rest.editMonth,editTimes:Number,editorSuffix:rest.editorSuffix,normalProductName:rest.normalProductName,editorName:rest.editorName,editorOneName:rest.editorOneName。editorTwoName:rest.editorTwo2ame,editType:rest.editType,platforms:rest.platforms,extendOne:rest.extendOne,extendTwo:rest.extendTwo,createTime:rest.createTime,coverUrl,width:meta.width,height:meta.height,videoSize:meta.videoSize,duration:Number)
}).n{failedCount++;} else{completedCount++;} }),remainingInfos.splice;不过,// 成功后移除
}catch{
console.error;failedCount++;remainingInfos.splice;// 防止死循环,可改为保留重试策略
}
// 实时广播给 UI
eventBus.emit('BATCH_UPLOAD_VIDEOS_WORKER',{
parseCount:cacheVideoData.parseCount。failedCount,successCount:completedCount,repeatCount,remainingCount:remainingInfos.length
});说起来,}
// 将最新状态写回 IndexedDB
const expireTime=moment.endOf.valueOf-moment.valueOf;await idbStore.setData('MuVideo/videoFiles',{
videoInfos:remainingInfos。parseCount:cacheVideoData.parseCount,failedCount,successCount:completedCount,repeatCount},expireTime);// 弹出桌面通知
if{
let title,msg;if{
title='素材同步完成';msg=`共成功上传 ${completedCount} 个视频,点击查看素材库`;}else if{
title='素材同步完成';msg=`成功 ${completedCount} 个,重复 ${repeatCnt} 个`;}else if{
title='所有素材已存在';msg=`共发现 ${repeatCnt} 个重复视频,已过滤`;}else{
title='素材同步出现异常';msg=`共 ${totalCount} 个,其中失败 ${failedCnt} 个`;}
this.showNotification;}
}
/** 启动定时检查 & 推送 */
async start{
ifreturn;if{ const ok=await this.register;ifreturn,}
const permOk=await this.requestPermission;ifreturn,this.isRunning=true;await this.checkAndSendNotifications;this.timer=setInterval=>this.checkAndSendNotifications,intervalMs);}
/** 停止轮询 */
stop{
clearInterval;this.timer=null;this.isRunning=false;}
/** 请求桌面通知权限 */
async requestPermission{
if){ console.warn;return false;}
const p=await Notification.requestPermission;return p==='granted';说起来,}
}
// 单例导出供全局调用
export const batchUploadVideosWorker=new BatchUploadVideosWorker;export const starBatchUploadVideosWorker==>batchUploadVideosWorker.start;export const stopBatchUploadVideosWorker==>batchUploadVideosWorker.stop;// 项目入口示例:页面加载后立即开启后台任务
setTimeout=>starBatchUploadVideosWorker,2000);
// 在业务代码任意位置广播进度:
eventBus.emit('BATCH_UPLOAD_VIDEOS_WORKER'。{
parseCount : cacheVideoData.parseCount,failedCount,successCount : completedCount,repeatCount,remaining Count : remainingInfos.length
});// UI 层监听并更新进度条:
eventBus.on('BATCH_UPLOAD_VIDEOS_WORKER',data=>{
updateProgressBar;// 自定义 UI 更新函数
});不过,
/** 使用者选择文件夹并持久化句柄 + 收集视频元信息 */
const handleFolderSelect = async => {
try{
// ✅ 打开目录选择器。获得 FileSystemDirectoryHandle
const dirHandle=await window.showDirectoryPicker;其实,// 将句柄保存到 IndexedDB。以便下次直接读取
await saveHandle;/** 深度遍历目录 → 收集所有文件对象 */
const allFiles=;const traverse=async =>{
for await){
const curPath=path?`${path}/${entry.name}`:`${entry.name}`;老实说,if{
const file=await entry.getFile;怎么说呢,allFiles.push({
name : entry.name,path : curPath,file。size : file.size,type : file.type,lastModified : file.lastModified
});}else{
await traverse;// 子目录递归
}
}
};await traverse;console.log,/** 🎯 筛选出常见的视频格式 */
const exts=;const videos=allFiles.filter).toLowerCase));console.log,/** 并行获取每个视频的宽高、时长等元信息 */
const videoInfos=await Promise.all=>{
const meta=await getVideoFileInfo;return{
fileName:name,filePath:path,file,width :meta.width。height :meta.height,videoSize:file.size,duration :meta.duration
};})),return videoInfos;话说回来,}catch{
if console.log;else console.error;return,}
};
| 对比维度 | 🔗 存储句柄 | 📦 存储文件内容 |
|---|---|---|
| 主要定义 ⚙️ | 轻量级引用指针,仅记录方法、权限等元信息。 | 完整二进制数据,即原始字节流。 |
| 典型存放位置 🗂️ | IDB + SessionStorage |
IDB |
| 数据大小范围 📏 | K ≤ 数据量 ≤ ~5KB | K → GB |
| 获取方式 🔍 | ✔ 必须重新授权
• 调用 |
✔ 可直接从 IndexedDB 按 Key 同步读取,无需使用者交互。 |
| 网络传输特性 🚚 | ⚡ 极低开销,仅传递句柄标识。适用于跨设备同步引用, | 📦 高带宽消耗,需要完整二进制流。例如100MB 视频 ≈100MB 网络流量。 |
| 使用者交互要求 🧑💻 | ❗ 强制交互,每次使用前必须获得授权;有效期通常 ≤24 小时。 | ✅ 零交互,可在后台静默读写;适合离线缓存场景, |
| 技术限制 ⚠️ | • Storage Access API 权限策略约束 • 跨域/跨会话需重新授权 • 无法直接获取内容,只能拿到句柄对象。 | • 浏览器配额限制 • 大文件需分块写入 • 序列化/反序列化带来 CPU 开销。 |
| 适用场景示例 💡 | • 文件管理器方法记忆 • 跨页面共享访问权限 • 离线文档编辑器的目录引用。 | • 大文件分片上传预处理 • 完整媒体资源离线缓存 • End‑to‑End 加密的私有云存储。其实, |
Sessio nStorage 的作用:
<\/ul> <\/li>
作为专业的SEO优化服务提供商,我们致力于通过科学、系统的搜索引擎优化策略,帮助企业在百度、Google等搜索引擎中获得更高的排名和流量。我们的服务涵盖网站结构优化、内容优化、技术SEO和链接建设等多个维度。
| 服务项目 | 基础套餐 | 标准套餐 | 高级定制 |
|---|---|---|---|
| 关键词优化数量 | 10-20个核心词 | 30-50个核心词+长尾词 | 80-150个全方位覆盖 |
| 内容优化 | 基础页面优化 | 全站内容优化+每月5篇原创 | 个性化内容策略+每月15篇原创 |
| 技术SEO | 基本技术检查 | 全面技术优化+移动适配 | 深度技术重构+性能优化 |
| 外链建设 | 每月5-10条 | 每月20-30条高质量外链 | 每月50+条多渠道外链 |
| 数据报告 | 月度基础报告 | 双周详细报告+分析 | 每周深度报告+策略调整 |
| 效果保障 | 3-6个月见效 | 2-4个月见效 | 1-3个月快速见效 |
我们的SEO优化服务遵循科学严谨的流程,确保每一步都基于数据分析和行业最佳实践:
全面检测网站技术问题、内容质量、竞争对手情况,制定个性化优化方案。
基于用户搜索意图和商业目标,制定全面的关键词矩阵和布局策略。
解决网站技术问题,优化网站结构,提升页面速度和移动端体验。
创作高质量原创内容,优化现有页面,建立内容更新机制。
获取高质量外部链接,建立品牌在线影响力,提升网站权威度。
持续监控排名、流量和转化数据,根据效果调整优化策略。
基于我们服务的客户数据统计,平均优化效果如下:
我们坚信,真正的SEO优化不仅仅是追求排名,而是通过提供优质内容、优化用户体验、建立网站权威,最终实现可持续的业务增长。我们的目标是与客户建立长期合作关系,共同成长。
Demand feedback