Firefox 插件开入门教程

Firefox 插件开入门教程

一、插件基本结构
一个最简单的 Firefox 插件需要以下文件:
my-extension/├── manifest.json # 插件配置文件(必需)├── icons/│ └── icon.svg # 插件图标├── popup/│ ├── popup.html # 弹出窗口│ ├── popup.js # 弹出窗口逻辑│ └── popup.css # 弹出窗口样式└── content/└── content.js # 内容脚本(操作网页)
二、manifest.json 详解
{"manifest_version":2,"name":"我的第一个插件","version":"1.0","description":"这是一个示例插件","icons":{"48":"icons/icon.svg"},"permissions":["activeTab","clipboardRead","clipboardWrite","notifications","downloads","scripting"],"browser_action":{"default_icon":"icons/icon.svg","default_title":"点击打开","default_popup":"popup/popup.html"},"content_scripts":[{"matches":["<all_urls>"],"js":["content/content.js"],"run_at":"document_end"}]}
关键字段说明:
manifest_version
: 使用版本 2(Firefox 支持) permissions
: 插件需要的权限 browser_action
: 点击工具栏图标时的行为 content_scripts
: 注入到网页中的脚本
三、开发环境搭建
1. 安装 Firefox 开发者版本(可选)
-
下载地址:https://www.mozilla.org/firefox/developer/ -
开发者版本允许加载未签名的扩展
2. 打开 about:debugging
在地址栏输入 about:debugging#/runtime/this-firefox
3. 加载临时扩展
-
点击”临时加载附加组件” -
选择插件文件夹中的 manifest.json文件 -
插件会立即加载并显示在列表中
四、调试技巧
1. 查看控制台日志
Content Script(内容脚本):
按 F12 打开开发者工具
-
切换到”控制台”标签 -
可以看到 content.js中的console.log输出
Popup(弹出窗口):
-
右键点击插件图标 -
选择”检查弹出窗口” -
会打开独立的开发者工具窗口
Background Script(后台脚本):
-
在 about:debugging页面 -
找到你的插件,点击”检查” -
打开后台脚本的开发者工具
2. 常用调试方法
// content.js 示例console.log("[MyExtension] 页面加载完成");console.log("[MyExtension] 当前URL:",window.location.href);// 查看元素constbuttons=document.querySelectorAll('button');console.log("[MyExtension] 找到按钮数量:",buttons.length);// 追踪错误try{// 可能出错的代码riskyFunction();}catch(err){console.error("[MyExtension] 错误:",err);}
3. 使用浏览器 API
// 显示通知browser.notifications.create({type:"basic",iconUrl:browser.runtime.getURL("icons/icon.svg"),title:"提示",message:"操作成功!"});// 读取剪贴板navigator.clipboard.readText().then(text=>{console.log("剪贴板内容:",text);});// 写入剪贴板navigator.clipboard.writeText("要复制的内容");
五、常见问题解决
问题1:Content Script 不执行
检查:
manifest.json
中的 matches是否匹配当前页面run_at
设置( document_start/document_end/document_idle)
问题2:权限不足
解决: 在 manifest.json 的 permissions 数组中添加所需权限
问题3:样式不生效
解决: 使用 !important 或检查选择器优先级
.my-element{background:red!important;z-index:999999!important;}
问题4:消息传递失败
检查:
// 确保 content script 已加载browser.tabs.sendMessage(tabId,{action:"test"}).catch(err=>{console.error("发送失败:",err);});
六、实战示例:创建一个简单的文本收集器
1. manifest.json
{"manifest_version":2,"name":"文本收集器","version":"1.0","description":"收集网页中选中的文本","permissions":["activeTab","clipboardWrite"],"browser_action":{"default_icon":"icons/icon.svg","default_title":"收集文本"},"content_scripts":[{"matches":["<all_urls>"],"js":["content.js"]}]}
2. content.js
(function(){// 创建侧边栏functioncreateSidebar(){constsidebar=document.createElement('div');sidebar.id='text-collector';sidebar.style.cssText=`position: fixed;top: 0;right: 0;width: 300px;height: 100vh;background: white;border-left: 1px solid #ccc;z-index: 999999;padding: 20px;box-shadow: -2px 0 8px rgba(0,0,0,0.1);`;sidebar.innerHTML=`<h3>收集的文本</h3><textarea id="collected-text" style="width: 100%; height: 300px;"></textarea><button id="copy-btn">复制全部</button>`;document.body.appendChild(sidebar);// 复制按钮sidebar.querySelector('#copy-btn').addEventListener('click',()=>{consttext=sidebar.querySelector('#collected-text').value;navigator.clipboard.writeText(text);alert('已复制!');});}// 监听来自 popup 的消息browser.runtime.onMessage.addListener((message)=>{if(message.action==="toggleSidebar"){constexisting=document.getElementById('text-collector');if(existing){existing.remove();}else{createSidebar();}}});console.log("[TextCollector] 已加载");})();
3. popup.js
document.addEventListener('DOMContentLoaded',()=>{browser.tabs.query({active:true,currentWindow:true}).then(tabs=>{browser.tabs.sendMessage(tabs[0].id,{action:"toggleSidebar"});window.close();});});
七、发布插件
-
打包插件:将文件夹压缩为 .zip文件 -
注册 Firefox 开发者账号:https://addons.mozilla.org/developers/ -
提交插件进行审核 -
审核通过后即可在插件商店发布
八、学习资源
-
MDN Web Docs: https://developer.mozilla.org/zh-CN/docs/Mozilla/Add-ons/WebExtensions -
Firefox 扩展工作坊: https://extensionworkshop.com/ -
示例扩展: https://github.com/mdn/webextensions-examples
夜雨聆风