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

如何在Chrome扩展中用JSON列表作为JS的switch-case匹配参数

批量处理多网站的Chrome扩展实现方案

一、JSON配置文件编写方案

创建site-config.json文件,按以下格式存储所有目标网站的配置,每个条目包含网站域名和对应站点名称(用于generateHTML的参数):

[
  {
    "hostname": "www.youtube.com",
    "siteName": "YouTube"
  },
  {
    "hostname": "www.google.com",
    "siteName": "Google"
  },
  {
    "hostname": "www.github.com",
    "siteName": "GitHub"
  }
]

二、JavaScript核心逻辑实现

替换原有的switch判断代码,改为加载JSON配置后批量处理的逻辑:

// 加载本地JSON配置文件
fetch(chrome.runtime.getURL('site-config.json'))
  .then(response => response.json())
  .then(sites => {
    const currentHost = window.location.hostname;
    // 匹配当前网站的配置
    const matchedSite = sites.find(site => site.hostname === currentHost);
    if (matchedSite) {
      document.head.innerHTML = generateSTYLES();
      document.body.innerHTML = generateHTML(matchedSite.siteName);
    }
  })
  .catch(error => console.error('加载配置文件失败:', error));

关键配置说明

  • 需将site-config.json添加到扩展manifest.json的web_accessible_resources中,确保内容脚本能正常加载:
    "web_accessible_resources": [
      {
        "resources": ["site-config.json"],
        "matches": ["<all_urls>"]
      }
    ]
    
  • 根据脚本运行需求,可在manifest.json中设置内容脚本的run_at参数(如"document_start"),保证能正确操作document.head和document.body。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 06:27:01