浏览器拓展开发的特殊数据持久化处理

Kaz
BrowserExtension
# Note# TS

示例:结合vueuse实现主题值持久化到拓展空间

由于vueuse的useColorMode持久化的目标是localstorage,我们需要修改到浏览器拓展的储存空间中,所以特地做以下处理。

import { AppTheme } from '~/types/ui/theme'
import { useColorMode } from '@vueuse/core'

/** 最终持久化到的位置(注意前缀需要按照浏览器规范) */
const STORAGE_APP_THEME = 'sync:theme'
/** 主题本地默认值 */
const DEFAULT_THEME = 'auto' satisfies AppTheme

// 浏览器拓展独立存储空间
export const extentStorageTheme = storage.defineItem<AppTheme>(STORAGE_APP_THEME)

// 建立一個 ref 來當作 useColorMode 的 storageRef
// 初始值先用 DEFAULT_THEME,之後由 watch 同步
const themeRef = ref<AppTheme>(DEFAULT_THEME)
// 從 storage 讀取真實值(只做一次)
;(async () => {
  const stored = await extentStorageTheme.getValue()
  if (stored) {
    themeRef.value = stored
  }
})()

// 监听临时值变化,同步改变拓展值
watch(
  themeRef,
  async newValue => {
    await extentStorageTheme.setValue(newValue)
  },
  { immediate: false },
)

/** 最终供外部用的主题值ref */
export const theme = useColorMode<AppTheme>({
  // 基于自定义ref桥接拓展空间
  storageRef: themeRef,
  // 不再持久化到"本地储存空间",因为是浏览器拓展环境
  storageKey: null,
  // 在绑定自定义ref的情况下,需要开启以允许auto值
  emitAuto: true,
})

export default theme

Copyright © 2025 KAZE. All rights reserved.