音频抓取助手 Chrome 浏览器扩展程序详解
全面解析与实现指南,助您轻松抓取网页音频资源
关键要点
- 自动检测音频资源:扩展程序能够自动扫描并识别当前网页中的所有音频资源。
- 实时徽章更新:通过图标徽章实时显示当前页面检测到的音频数量,提升用户体验。
- 便捷下载功能:用户可在 Popup 界面中一键下载所有检测到的音频资源,操作简便高效。
扩展程序架构概述
“音频抓取助手”是一款基于 Manifest V3 规范的 Chrome 浏览器扩展程序。其主要功能包括自动检测网页中的音频资源、在扩展图标上显示音频数量徽章以及提供便捷的下载界面。以下将详细介绍各个组成部分及其实现细节。
1. manifest.json
扩展配置文件
这是扩展程序的核心配置文件,定义了扩展的基本信息、必要权限及脚本文件的加载方式。
{
"manifest_version": 3,
"name": "音频抓取助手",
"version": "1.0.0",
"description": "自动检测并下载网页中的音频资源",
"permissions": [
"activeTab",
"tabs",
"downloads",
"scripting"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup/popup.html",
"default_icon": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"]
}],
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
}
关键字段解释:
manifest_version:指定使用的 Manifest 版本。name、version、description:定义扩展的基本信息。permissions:声明扩展所需的权限,如访问标签页、下载权限等。background:指定后台脚本文件,用于处理消息传递和资源管理。action:定义扩展图标的行为,包括默认弹出页面和图标。content_scripts:指定内容脚本的注入方式和匹配的网页URL。icons:提供不同尺寸的扩展图标。
2. background.js
后台脚本
后台脚本负责管理各个标签页的音频资源、更新扩展图标的徽章以及处理下载请求。它通过监听来自内容脚本和 Popup 界面的消息,实现功能的协同运作。
// 存储每个标签页的音频资源列表
const audioResources = {};
// 监听来自 Content Script 的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
const tabId = sender.tab.id;
if (message.type === "audioList") {
// 更新当前标签页的音频资源列表
audioResources[tabId] = message.audioUrls;
// 更新徽章显示
if (message.audioUrls.length > 0) {
chrome.action.setBadgeText({ text: message.audioUrls.length.toString(), tabId });
chrome.action.setBadgeBackgroundColor({ color: "#4CAF50", tabId });
} else {
chrome.action.setBadgeText({ text: "", tabId });
}
} else if (message.type === "downloadAudio") {
// 处理下载请求
chrome.downloads.download({
url: message.audioUrl,
filename: message.filename
});
} else if (message.type === "getAudioList") {
// 返回音频列表给 Popup
sendResponse({ audioUrls: audioResources[tabId] || [] });
}
});
// 监听标签页更新事件
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === "complete") {
// 重新注入 Content Script 以检测音频资源
chrome.scripting.executeScript({
target: { tabId },
files: ["content.js"]
});
}
});
// 监听标签页激活事件
chrome.tabs.onActivated.addListener((activeInfo) => {
const tabId = activeInfo.tabId;
// 更新徽章显示
if (audioResources[tabId] && audioResources[tabId].length > 0) {
chrome.action.setBadgeText({ text: audioResources[tabId].length.toString(), tabId });
chrome.action.setBadgeBackgroundColor({ color: "#4CAF50", tabId });
} else {
chrome.action.setBadgeText({ text: "", tabId });
}
});
// 监听标签页关闭事件
chrome.tabs.onRemoved.addListener((tabId) => {
// 清除存储的音频资源列表
delete audioResources[tabId];
});
功能详解:
- 音频资源管理:通过
audioResources对象,后台脚本能够高效地存储和管理每个标签页的音频资源列表。 - 消息监听:使用
chrome.runtime.onMessage监听来自内容脚本和 Popup 的消息,进行相应的处理。 - 徽章更新:根据检测到的音频数量,实时更新扩展图标上的徽章,提供直观的用户反馈。
- 下载处理:响应用户在 Popup 界面发起的下载请求,利用
chrome.downloads.download()API 实现音频文件的下载。 - 事件监听:监听标签页的更新、激活和关闭事件,确保音频资源的实时检测和管理。
3. content.js
内容脚本
内容脚本负责在用户浏览网页时,自动扫描并检测页面中的音频资源。它会查找所有的 <audio> 和 <video> 标签,并提取其中的音频URL,随后将这些信息传递给后台脚本。
// 检测页面中的音频资源
function detectAudioResources() {
const audioUrls = [];
// 查找所有 <audio> 标签
document.querySelectorAll("audio").forEach((audio) => {
if (audio.src) {
audioUrls.push(audio.src);
}
// 检查 <source> 子标签
audio.querySelectorAll("source").forEach((source) => {
if (source.src) {
audioUrls.push(source.src);
}
});
});
// 查找所有 <video> 标签
document.querySelectorAll("video").forEach((video) => {
if (video.src) {
audioUrls.push(video.src);
} else {
const source = video.querySelector("source");
if (source && source.src) {
audioUrls.push(source.src);
}
}
});
// 发送检测到的音频资源列表给 Background Script
chrome.runtime.sendMessage({
type: "audioList",
audioUrls: audioUrls
});
}
// 页面加载完成后执行检测
detectAudioResources();
// 监听 DOM 变化,动态检测新增的音频资源
const observer = new MutationObserver(detectAudioResources);
observer.observe(document.body, { childList: true, subtree: true });
功能详解:
- 音频资源扫描:通过查询所有
<audio>和<video>标签,提取其src属性或子标签<source>的src属性。 - 动态检测:利用
MutationObserver监听 DOM 变化,确保动态添加的音频资源也能被检测到。 - 消息传递:通过
chrome.runtime.sendMessage将检测到的音频URL列表发送给后台脚本,进行进一步处理。
4. popup/popup.html
Popup 界面 HTML
这是用户与扩展程序交互的主要界面。当用户点击扩展图标时,Popup 界面会显示所有检测到的音频资源,并提供下载按钮。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>音频抓取助手</title>
<link rel="stylesheet" href="popup.css">
</head>
<body>
<div id="loading">加载中...</div>
<ul id="audio-list"></ul>
<script src="popup.js"></script>
</body>
</html>
功能详解:
- 结构简洁:界面包含一个加载状态提示和一个用于展示音频列表的无序列表。
- 样式引入:通过链接外部 CSS 文件
popup.css进行样式设置,确保界面美观统一。 - 脚本引入:引入
popup.js实现动态内容的加载和用户交互。
5. popup/popup.css
Popup 界面 CSS
该 CSS 文件负责 Popup 界面的样式设计,确保界面简洁美观且用户友好。
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 10px;
width: 300px;
background-color: #fff;
}
#loading {
text-align: center;
padding: 10px;
color: #555;
}
#audio-list {
list-style: none;
padding: 0;
margin: 0;
}
#audio-list li {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
border-bottom: 1px solid #ddd;
}
#audio-list li:last-child {
border-bottom: none;
}
button {
background-color: #4CAF50;
color: white;
border: none;
padding: 5px 10px;
cursor: pointer;
border-radius: 3px;
}
button:hover {
background-color: #45a049;
}
功能详解:
- 整体布局:设置了统一的字体、边距和背景颜色,确保界面整洁。
- 加载状态:通过
#loadingID 的样式,明确展示加载中的提示信息。 - 音频列表:列表项采用灵活布局,音频名称与下载按钮分列显示,提升用户体验。
- 按钮样式:下载按钮采用绿色主题,颜色变化提供交互反馈,增强可用性。
6. popup/popup.js
Popup 界面 JavaScript
该 JavaScript 文件负责在 Popup 界面加载时获取当前标签页的音频资源列表,并动态展示在界面上。同时,它处理用户的下载请求,向后台脚本发送相应的消息。
document.addEventListener("DOMContentLoaded", () => {
const audioList = document.getElementById("audio-list");
const loading = document.getElementById("loading");
// 获取当前激活的标签页
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const tabId = tabs[0].id;
// 向 Background Script 请求音频资源列表
chrome.runtime.sendMessage({ type: "getAudioList", tabId }, (response) => {
loading.style.display = "none";
if (response && response.audioUrls && response.audioUrls.length > 0) {
// 显示音频资源列表
response.audioUrls.forEach((audioUrl) => {
const li = document.createElement("li");
// 提取文件名
const filename = audioUrl.split("/").pop() || "未知音频";
// 显示文件名
const span = document.createElement("span");
span.textContent = filename;
li.appendChild(span);
// 添加下载按钮
const button = document.createElement("button");
button.textContent = "下载";
button.addEventListener("click", () => {
chrome.runtime.sendMessage({
type: "downloadAudio",
audioUrl: audioUrl,
filename: filename
});
});
li.appendChild(button);
audioList.appendChild(li);
});
} else {
// 显示无音频资源的提示
const noAudio = document.createElement("div");
noAudio.textContent = "未检测到音频资源";
noAudio.style.textAlign = "center";
noAudio.style.color = "#777";
audioList.appendChild(noAudio);
}
});
});
});
功能详解:
-
页面加载事件:通过监听
DOMContentLoaded事件,确保在页面内容加载完毕后执行脚本。 -
获取音频列表:利用
chrome.tabs.query获取当前激活标签页的 ID,随后向后台脚本请求该标签页的音频资源列表。 -
动态生成列表项:对于每个音频URL,创建一个列表项,包括音频名称和下载按钮。
-
下载事件处理:当用户点击下载按钮时,发送
downloadAudio类型的消息,传递音频URL和文件名给后台脚本处理下载。 -
无音频提示:如果未检测到任何音频资源,界面会显示相应的提示信息,提升用户体验。
文件结构
为了确保扩展程序的有序性和可维护性,建议采用以下的文件目录结构:
| 目录/文件 | 说明 |
|---|---|
| audio-capture-assistant/ | 根目录 |
| ├── manifest.json | 扩展配置文件 |
| ├── background.js | 后台脚本 |
| ├── content.js | 内容脚本 |
| ├── icons/ | 存放扩展图标 |
| │ ├── icon16.png | 16x16 图标 |
| │ ├── icon48.png | 48x48 图标 |
| │ └── icon128.png | 128x128 图标 |
| └── popup/ | 存放 Popup 界面文件 |
| ├── popup.html | Popup 界面 HTML |
| ├── popup.css | Popup 界面 CSS |
| └── popup.js | Popup 界面 JavaScript |
结论
“音频抓取助手”是一款功能强大的 Chrome 浏览器扩展程序,能够自动检测并管理网页中的音频资源。通过高效的内容脚本和后台脚本协同工作,结合简洁友好的 Popup 界面,用户可以轻松查看和下载网页中的所有音频文件。该扩展程序不仅提升了用户的浏览体验,还为需要抓取音频资源的用户提供了极大的便利。
安装与使用指南:
- 将以上所有文件按照文件结构保存至一个文件夹,例如
audio-capture-assistant。 - 准备好所需尺寸的图标文件,并将其放置在
icons文件夹内。 - 打开 Chrome 浏览器,进入
chrome://extensions/页面。 - 启用右上角的 开发者模式。
- 点击 “加载已解压的扩展程序”,选择存放扩展程序文件的文件夹。
- 加载成功后,扩展图标将出现在浏览器工具栏中。点击图标即可查看和下载当前页面的音频资源。
参考资源
为了进一步了解 Chrome 扩展程序的开发,以下是一些有用的参考资源:
Last updated January 19, 2025