chrome如何编写一个录屏插件?
网友回复
我们从零开始的、详细的、分步的教程,来创建一个基础的录屏插件。这个插件将能够:
点击浏览器工具栏的图标,弹出一个小窗口。
在小窗口中点击“开始录制”按钮,触发浏览器原生屏幕选择界面。
用户选择要录制的屏幕、窗口或标签页后,开始录制。
点击“停止录制”按钮,结束录制。
生成一个可下载的视频文件(通常是 .webm 格式)。
我们将使用 Manifest V3,这是当前 Chrome 扩展的最新标准。
第一步:创建项目结构
首先,在你的电脑上创建一个新的文件夹,比如 screen-recorder-extension。然后在这个文件夹里,创建以下文件和目录
icons/: 你可以先用任意图片作为占位符,或者从网上找一些免费图标。这些图标会显示在浏览器工具栏和扩展管理页面。
第二步:编写 manifest.json (清单文件)
这是扩展的核心配置文件,它告诉 Chrome 关于这个插件的所有信息,包括名称、权限、脚本等。manifest.json
{ "manifest_version": 3, "name": "简易录屏插件", "version": "1.0", "description": "一个简单的Chrome录屏插件,使用 getDisplayMedia API。", "permissions": [ "storage" ], "background": { "service_worker": "background.js" }, "action": { "default_popup": "popup.html", "default_icon": { "16": "icons/icon16.png", "48": "icons/icon48.png", "128": "icons/icon128.png" } }, "icons": { "16": "icons/icon16.png", "48": "icons/icon48.png", "128": "icons/icon128.png" } }关键点解释:
"manifest_version": 3: 声明我们使用 Manifest V3。
"permissions": ["storage"]: 我们请求 storage 权限,用来在不同脚本之间(比如 popup 和 background)同步录制状态。
"background": { "service_worker": "background.js" }: 指定 background.js 作为我们的 Service Worker。在 V3 中,后台脚本在需要时运行,而不是持续存在,这对于处理录制这种需要持久状态的任务至关重要。
"action": { ... }: 定义了用户在浏览器工具栏上看到和交互的内容。点击图标时,会弹出 popup.html。
第三步:创建用户界面 (popup.html 和 popup.js)
这是用户直接交互的部分。
popup.html
<!DOCTYPE html> <html> <head> <title>录屏插件</title> <style> body { width: 200px; font-family: sans-serif; text-align: center; } button { width: 120px; margin: 5px; padding: 10px; } #status { font-weight: bold; margin: 10px 0; } #downloadLink { display: none; } </style> </head> <body> <h3>简易录屏</h3> <p id="status">空闲</p> <button id="startBtn">开始录制</button> <button id="stopBtn" disabled>停止录制</button> <a id="downloadLink" download="recording.webm">下载视频</a> </body> <script src="popup.js"></script> </html>popup.js
这个脚本负责处理 popup.html 中的按钮点击事件,并与后台脚本 background.js 通信。
const startBtn = document.getElementById('startBtn'); const stopBtn = document.getElementById('stopBtn'); const status = document.getElementById('status'); const downloadLink = document.getElementById('downloadLink'); // 更新UI状态 function updateUI(isRecording, videoUrl = null) { startBtn.disabled = isRecording; stopBtn.disabled = !isRecording; status.textContent = isRecor...
点击查看剩余70%