开发读取audio标签内音频文件名的浏览器扩展,求入门指导
开发浏览器扩展读取Audio标签音频文件名指南
一、搭建扩展基础结构
先创建一个扩展文件夹,里面包含三个核心文件:
manifest.json:扩展配置文件,定义权限、注入规则等核心信息content.js:注入目标网页的脚本,负责读取页面内的audio标签popup.html(可选):点击扩展图标时弹出的界面,用于展示提取到的文件名
二、编写manifest.json配置
根据目标浏览器(Chrome/Edge/Firefox)编写配置,示例如下:
{ "manifest_version": 3, "name": "音频文件名提取工具", "version": "1.0", "description": "提取网页audio标签中的音频文件名", "permissions": ["activeTab"], "content_scripts": [ { "matches": ["<all_urls>"], // 可指定特定网站,例如"https://xxx.com/*" "js": ["content.js"] } ], "action": { "default_popup": "popup.html" } }
注:Chrome/Edge推荐用manifest_version 3;Firefox部分版本兼容v3,也可改用v2并调整对应字段
三、编写content.js读取audio标签
脚本注入网页后,可通过选择器定位audio标签,提取src属性并解析文件名:
// 定位目标audio标签(按id查找) const audioTag = document.getElementById('jp_audio_1'); if (audioTag) { const src = audioTag.src; // 从路径中提取文件名,兼容绝对/相对路径 const fileName = src.split('/').pop(); console.log('提取到的音频文件名:', fileName); // 若需传递给弹窗,可发送消息 chrome.runtime.sendMessage({fileName: fileName}); }
如果要批量处理所有audio标签,改用遍历逻辑:
const audioTags = document.querySelectorAll('audio'); audioTags.forEach(tag => { const src = tag.src; const fileName = src.split('/').pop(); console.log(`音频文件名:${fileName}`); });
四、编写popup.html(可选)
若要通过弹窗展示结果,编写简单的弹窗页面:
<!DOCTYPE html> <html> <head> <style> body {width: 220px; padding: 12px; margin: 0;} </style> </head> <body> <div id="result"></div> <script> // 接收content.js传来的文件名 chrome.runtime.onMessage.addListener((message) => { document.getElementById('result').textContent = `提取结果:${message.fileName}`; }); // 弹窗打开时主动触发一次读取 chrome.tabs.query({active: true, currentWindow: true}, (tabs) => { chrome.scripting.executeScript({ target: {tabId: tabs[0].id}, function: getAudioFileName }); }); function getAudioFileName() { const audioTag = document.getElementById('jp_audio_1'); if (audioTag) { const fileName = audioTag.src.split('/').pop(); chrome.runtime.sendMessage({fileName: fileName}); } else { chrome.runtime.sendMessage({fileName: '未找到目标audio标签'}); } } </script> </body> </html>
五、加载扩展到浏览器
- Chrome/Edge:打开浏览器「扩展」页面 → 开启「开发者模式」→ 点击「加载已解压的扩展程序」,选择你的扩展文件夹
- Firefox:打开「附加组件和主题」→ 右上角设置 → 「调试附加组件」→ 「临时加载附加组件」,选择manifest.json文件
六、处理动态加载的audio标签
如果audio标签是页面动态生成的,可通过DOM监听实现自动提取:
const observer = new MutationObserver((mutations) => { mutations.forEach(mutation => { if (mutation.addedNodes.length) { const audioTag = document.getElementById('jp_audio_1'); if (audioTag) { const fileName = audioTag.src.split('/').pop(); console.log('动态加载的音频文件名:', fileName); observer.disconnect(); // 找到目标后停止监听,按需调整 } } }); }); observer.observe(document.body, {childList: true, subtree: true});
内容的提问来源于stack exchange,提问作者NightShadeTVN
相关产品推荐
相关产品推荐

