如何将Manifest V3版本Chrome扩展连接到Firestore数据库
方案1:使用Firebase v9+ 模块化SDK(推荐)
v9及以上版本的Firebase模块化SDK已放弃对XMLHttpRequest的依赖,全部改用标准fetch API,完美兼容MV3的Service Worker环境,体积也比旧版SDK更小。
具体操作步骤如下:
- 在
manifest.json中配置相关权限和background规则:
{ "manifest_version": 3, // 其余扩展配置省略 "background": { "service_worker": "background.js", "type": "module" }, "host_permissions": [ "https://firestore.googleapis.com/*" ] }
- 从官方渠道下载Firebase模块化SDK的单文件版本,放到扩展的
firebase目录下,在background.js中直接导入初始化即可:
import { initializeApp } from './firebase/firebase-app.js'; import { getFirestore, collection, getDocs } from './firebase/firebase-firestore.js'; // 替换为你自己的Firebase项目配置 const firebaseConfig = { apiKey: "你的项目API_KEY", projectId: "你的项目ID", // 其余配置项按需补充 }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); // 测试读取数据 async function fetchData() { const snapshot = await getDocs(collection(db, "你的集合名称")); snapshot.forEach(doc => console.log(doc.id, doc.data())); }
方案2:直接调用Firestore REST API(轻量场景可选)
如果你只需要简单的读写、不需要实时监听等高级能力,可以直接调用官方REST接口,不需要引入任何SDK,完全规避兼容问题,示例代码:
async function readDoc(collectionName, docId) { const projectId = "你的项目ID"; const apiKey = "你的项目API_KEY"; const url = `https://firestore.googleapis.com/v1/projects/${projectId}/databases/(default)/documents/${collectionName}/${docId}?key=${apiKey}`; const res = await fetch(url); return await res.json(); }
关于你提到的备选方案可行性
你所说的「Firestore同步到实时数据库再对接扩展」的方案本身是可以正常运行的,但会额外增加数据维护成本,还要处理双数据库同步的一致性问题,性价比很低,优先选用上面两个直接对接Firestore的方案即可。
内容的提问来源于stack exchange,提问作者bnsmcx
相关产品推荐
相关产品推荐

