如何在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
相关产品推荐
相关产品推荐

