You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Chrome Extension Manifest V3中连接Firestore数据库

解决方案

1. 正确引入Firebase ES模块

Manifest V3的Service Worker采用模块模式,不能直接使用npm包导入,需下载Firebase的ES模块文件到本地:

  • 下载Firebase官方提供的ES模块包,解压后将firebase-app.js、firebase-firestore.js等所需文件放入扩展目录的lib文件夹。
  • 修改background.js的导入路径为本地文件:
import { initializeApp } from './lib/firebase-app.js';
import { getFirestore, query, collection, where, getDocs } from './lib/firebase-firestore.js';

const firebaseConfig = {
  // 你的Firebase项目配置
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

2. 调整Manifest配置

Manifest V3默认CSP(内容安全策略)严格,需添加Firebase相关权限和规则:

{
  "manifest_version": 3,
  "name": "extension try 5000",
  "version": "1.0",
  "description": "My first Chrome extension",
  "action": {
    "default_popup": "popup.html",
    "default_icon": "icon.png"
  },
  "permissions": ["scripting"],
  "host_permissions": [
    "https://*.firebaseio.com/*",
    "https://*.firestore.googleapis.com/*"
  ],
  "background": {
    "service_worker": "background.js",
    "type": "module"
  },
  "content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'none'; connect-src https://*.firebaseio.com https://*.firestore.googleapis.com"
  }
}
  • 缩小host_permissions到Firebase专属域名,避免过度授权。
  • content_security_policy中的connect-src允许Firebase API请求。

3. 实现Popup与Background的消息通信

Popup负责用户交互(输入、结果展示),Background处理Firestore查询,通过Chrome消息API传递数据:

3.1 Popup端代码

popup.html:

<!DOCTYPE html>
<html>
<head>
  <style>
    body { width: 300px; padding: 10px; }
    #searchInput { width: 100%; margin-bottom: 10px; padding: 8px; }
    #result { margin-top: 10px; }
  </style>
</head>
<body>
  <input type="text" id="searchInput" placeholder="输入搜索关键词">
  <button id="searchBtn">搜索</button>
  <div id="result"></div>
  <script src="popup.js"></script>
</body>
</html>

popup.js:

document.getElementById('searchBtn').addEventListener('click', async () => {
  const keyword = document.getElementById('searchInput').value.trim();
  if (!keyword) return;

  const response = await chrome.runtime.sendMessage({
    type: 'SEARCH_FIRESTORE',
    keyword: keyword
  });

  const resultDiv = document.getElementById('result');
  if (response.success) {
    resultDiv.innerHTML = response.data.map(item => `<p>${JSON.stringify(item)}</p>`).join('');
  } else {
    resultDiv.innerHTML = `<p>查询失败:${response.error}</p>`;
  }
});

3.2 Background端代码

在Firebase初始化代码后添加消息监听:

chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
  if (message.type === 'SEARCH_FIRESTORE') {
    try {
      // 根据你的数据结构调整查询逻辑
      const q = query(
        collection(db, '你的集合名称'),
        where('匹配字段名', '==', message.keyword)
      );
      const querySnapshot = await getDocs(q);
      const data = [];
      querySnapshot.forEach(doc => {
        data.push({ id: doc.id, ...doc.data() });
      });
      sendResponse({ success: true, data: data });
    } catch (error) {
      sendResponse({ success: false, error: error.message });
    }
    return true; // 标记为异步响应
  }
});

4. 关键注意事项

  • 调整Firebase项目的安全规则,确保扩展有权限访问数据(开发阶段可临时放宽,上线前必须收紧)。
  • 不要在Popup中初始化Firebase,因为Popup关闭后会销毁,重新打开会重复初始化;Background的Service Worker适合处理持久化连接。
  • 测试时打开Chrome扩展管理页面的开发者模式,加载已解压的扩展,通过"后台页面"入口查看Background的控制台日志。

内容的提问来源于stack exchange,提问作者Soderman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 21:47:07