如何开发可解析HTML并转换为ChordPro格式的Firefox扩展
实现方案:Firefox 网页和弦转 ChordPro 扩展
一、扩展基础结构
先搭建最简化的扩展骨架,包含3个核心文件:
manifest.json:扩展配置文件content-script.js:负责网页DOM解析的脚本popup.html+popup.js:触发解析和保存的交互界面
1. manifest.json 配置
{ "manifest_version": 3, "name": "和弦转ChordPro", "version": "1.0", "description": "提取网页和弦并转换为ChordPro格式", "permissions": ["activeTab", "downloads"], "action": { "default_popup": "popup.html" }, "content_scripts": [ { "matches": ["<all_urls>"], // 可改为目标网站的匹配规则,比如"*://*.example.com/*" "js": ["content-script.js"] } ] }
二、核心解析逻辑(content-script.js)
这个脚本直接运行在目标网页里,负责遍历DOM并转换格式:
- 找到所有带
.beginLine类的元素 - 逐个处理每个元素的子节点,区分普通文本和和弦节点
- 把和弦(包括
<sup>里的扩展音)合并成[和弦名]格式,插入到对应文本位置
// 转换单个.beginLine元素为ChordPro格式 function convertLineToChordPro(lineElement) { let result = ''; // 遍历当前元素的所有子节点(文本节点+元素节点) const childNodes = lineElement.childNodes; for (let node of childNodes) { if (node.nodeType === Node.TEXT_NODE) { // 普通文本直接追加 result += node.textContent.trim(); } else if (node.classList?.contains('chord')) { // 和弦节点,提取完整文本(含sup里的扩展音) const chordText = node.textContent.trim(); result += `[${chordText}]`; } } return result; } // 批量转换所有目标行 function convertAllLines() { const lineElements = document.querySelectorAll('.beginLine'); const chordProLines = []; for (let el of lineElements) { const converted = convertLineToChordPro(el); if (converted) chordProLines.push(converted); } return chordProLines.join('\n'); } // 监听来自popup的转换请求,返回结果 browser.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.type === 'convert') { const chordProContent = convertAllLines(); sendResponse(chordProContent); } });
三、交互与保存功能(popup.html + popup.js)
popup提供按钮触发解析并保存文件:
popup.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> body { width: 200px; padding: 15px; } button { width: 100%; padding: 8px; cursor: pointer; } </style> </head> <body> <button id="convertBtn">转换并保存ChordPro</button> <script src="popup.js"></script> </body> </html>
popup.js
document.getElementById('convertBtn').addEventListener('click', async () => { // 向当前标签页的content脚本发送转换请求 const [tab] = await browser.tabs.query({ active: true, currentWindow: true }); const response = await browser.tabs.sendMessage(tab.id, { type: 'convert' }); if (!response) { alert('未找到可转换的和弦内容'); return; } // 创建文件Blob并生成下载链接 const blob = new Blob([response], { type: 'text/plain' }); const url = URL.createObjectURL(blob); // 调用浏览器下载API保存文件 await browser.downloads.download({ url: url, filename: 'song-chords.pro', // 后缀用.pro或.txt均可 saveAs: true // 让用户选择保存位置 }); URL.revokeObjectURL(url); // 释放临时链接 });
四、测试与调试
- 把所有文件放在同一个文件夹中
- 打开Firefox,输入
about:debugging→ 此Firefox → 加载临时附加组件 → 选择文件夹里的manifest.json - 打开包含目标和弦的网页,点击扩展图标,点击按钮即可完成转换保存
五、简化优化建议(针对JS基础薄弱)
- 代码已用最基础的遍历和判断实现核心功能,无需复杂语法
- 如果目标网页和弦结构有变化,只需修改
convertLineToChordPro里的节点判断规则(比如和弦类名不是chord时,替换对应class) - 测试时可直接在浏览器控制台调用
convertAllLines(),查看转换结果是否正确
内容的提问来源于stack exchange,提问作者redmetz
相关产品推荐
相关产品推荐

