Chrome扩展点击按钮触发fetch、抓取进度条实现播放控制的方法问询
一、点击Chrome扩展弹窗按钮触发fetch请求的实现方案
当前Chrome扩展主流使用V3版本 manifest,实现步骤如下:
- 第一步:配置
manifest.json权限,确保你要请求的API域名被加入授权列表
{ "manifest_version": 3, "name": "自定义控制扩展", "version": "1.0", "action": { "default_popup": "popup.html" }, "host_permissions": ["https://你的API域名/*"], // 按需替换为实际API域名,全域名授权可填<all_urls> "permissions": ["activeTab", "scripting"] }
- 第二步:编写弹窗页面
popup.html,添加交互按钮
<!DOCTYPE html> <html> <body style="width: 300px; padding: 16px;"> <button id="playBtn">播放</button> <button id="apiCallBtn">触发API请求</button> <script src="popup.js"></script> </body> </html>
- 第三步:编写弹窗逻辑
popup.js,绑定点击事件触发fetch请求
document.getElementById('apiCallBtn').addEventListener('click', async () => { try { const response = await fetch('https://你的API接口地址', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ // 你的请求参数 }) }) const result = await response.json() console.log('请求成功返回:', result) } catch (error) { console.error('请求失败:', error) } })
只要manifest权限配置正确,弹窗上下文可直接发起跨域fetch请求,无需额外通过后台服务转发。
二、YouTube进度条同步&控制最优实现方案
不推荐爬取DOM进度条属性的方案,YouTube前端迭代频繁会导致DOM结构变动,最优方案是调用YouTube页面原生播放器API,稳定性最高,原生方法支持所有播放控制能力:
- 首先确认:YouTube页面的播放器实例绑定在
document.getElementById('movie_player')元素上,自带所有原生方法:- 读取当前播放进度:
player.getCurrentTime()单位为秒 - 读取总时长:
player.getDuration()单位为秒 - 跳转指定进度:
player.seekTo(目标秒数, true)第二个参数传true可实现精准跳转 - 播放/暂停控制:
player.playVideo()/player.pauseVideo()
- 读取当前播放进度:
- 进度同步推荐用100ms轮询的方案,比事件监听更稳定,不会因为播放器状态切换漏更新,开销极低对性能无影响
具体实现步骤
- 先在
manifest.json中添加内容脚本预注入配置,打开YouTube页面自动注入逻辑
{ // 其余manifest配置不变,新增如下项 "content_scripts": [ { "matches": ["*://*.youtube.com/*"], "js": ["content.js"] } ] }
- 编写内容脚本
content.js,负责和播放器交互、响应弹窗消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { const player = document.getElementById('movie_player') if (!player) return sendResponse({ success: false, msg: '未找到播放器' }) switch (request.action) { // 获取当前播放进度 case 'getProgress': sendResponse({ success: true, currentTime: player.getCurrentTime(), duration: player.getDuration() }) break // 跳转指定进度 case 'setProgress': player.seekTo(request.targetTime, true) sendResponse({ success: true }) break // 播放控制 case 'play': player.playVideo() sendResponse({ success: true }) break // 暂停控制 case 'pause': player.pauseVideo() sendResponse({ success: true }) break } return true // 异步返回必须添加该配置 })
- 在
popup.js中添加进度同步、控制逻辑
const progressBar = document.getElementById('progressBar') // 弹窗中的进度条元素 // 弹窗打开后每100ms同步一次播放进度 setInterval(async () => { const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true }) chrome.tabs.sendMessage(activeTab.id, { action: 'getProgress' }, (res) => { if (res?.success) { const progressPercent = (res.currentTime / res.duration) * 100 progressBar.value = progressPercent } }) }, 100) // 拖动弹窗进度条触发页面播放器跳转 progressBar.addEventListener('change', async (e) => { const targetPercent = e.target.value const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true }) chrome.tabs.sendMessage(activeTab.id, { action: 'getProgress' }, (res) => { if (res?.success) { const targetTime = (targetPercent / 100) * res.duration chrome.tabs.sendMessage(activeTab.id, { action: 'setProgress', targetTime }) } }) }) // 绑定播放按钮点击事件 document.getElementById('playBtn').addEventListener('click', async () => { const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true }) chrome.tabs.sendMessage(activeTab.id, { action: 'play' }) })
内容的提问来源于stack exchange,提问作者conayo
相关产品推荐
相关产品推荐

