You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展Manifest V3中content script调用chrome.tabCapture报undefined如何解决

问题根因

chrome.tabCapture 属于Chrome扩展私有API,仅允许在扩展的自有上下文(后台Service Worker、扩展弹窗页、扩展选项页等)中调用,你现在是在注入到网页的content script中调用该API,content script的权限受限,无法访问chrome.tabCapture对象,因此会抛出undefined报错,和manifest中是否配置了tabCapture权限无关。

解决步骤
  • 第一步:将chrome.tabCapture.capture的调用逻辑迁移到扩展的后台Service Worker中,如需从网页侧触发录屏,通过Chrome扩展的消息通信机制传递指令即可。
  • 第二步:如果需要把录制的视频数据回传给content script做后续处理,注意MediaStream对象无法直接通过消息通道传递,可以先通过MediaRecorder把流录制成二进制片段,再转成ArrayBuffer或Blob链接回传。

示例代码

content script(触发录屏)

// 向后台Service Worker发送录屏指令
chrome.runtime.sendMessage({
  action: 'startTabCapture',
  width: 1920,
  height: 1080,
  fps: 30
}, (res) => {
  if (res.status === 'success') {
    // 拿到录制完成的视频blob链接,可做预览、编辑等操作
    console.log('录屏完成,视频地址:', res.blobUrl)
  } else {
    console.error('录屏失败:', res.error)
  }
})

后台Service Worker(处理录屏逻辑)

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // 监听content script发送的录屏指令
  if (message.action !== 'startTabCapture') return

  const { width, height, fps } = message
  chrome.tabCapture.capture(
    {
      video: true,
      audio: true,
      videoConstraints: {
        mandatory: {
          chromeMediaSource: "tab",
          minWidth: width,
          minHeight: height,
          maxWidth: width,
          maxHeight: height,
          maxFrameRate: fps,
        },
      },
    },
    (stream) => {
      // 捕获调用异常
      if (chrome.runtime.lastError) {
        sendResponse({
          status: 'fail',
          error: chrome.runtime.lastError.message
        })
        return
      }

      // 用MediaRecorder录制视频流
      const mediaRecorder = new MediaRecorder(stream, {
        mimeType: 'video/webm;codecs=vp9'
      })
      const videoChunks = []

      mediaRecorder.ondataavailable = (e) => videoChunks.push(e.data)
      mediaRecorder.onstop = () => {
        // 录制结束生成blob链接返回给content script
        const videoBlob = new Blob(videoChunks, { type: 'video/webm' })
        const blobUrl = URL.createObjectURL(videoBlob)
        sendResponse({
          status: 'success',
          blobUrl: blobUrl
        })
        // 释放流资源
        stream.getTracks().forEach(track => track.stop())
      }

      mediaRecorder.start()
    }
  )
  // 异步返回结果需要return true,保持消息端口不被关闭
  return true
})
额外注意事项
  • Manifest V3的Service Worker是临时唤醒机制,没有常驻权限,如果需要长时间录屏,建议创建扩展的offscreen文档来持有MediaStream和MediaRecorder实例,避免Service Worker被系统自动回收导致录制中断。
  • 调用chrome.tabCapture需要用户主动交互触发(比如点击扩展图标、点击网页上的按钮),否则会触发权限拒绝错误。

内容的提问来源于stack exchange,提问作者Denis Dombrovski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 10:21:02