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

在TypeScript中调用clients.matchAll()报错:找不到名称'clients'

解决TypeScript错误:Cannot find name 'clients'.ts(2304)

原因分析

Chrome扩展的Service Worker环境中,clients是浏览器提供的全局API,但TypeScript默认不识别该特定全局对象,且不存在单独的"clients"类型包,你之前在tsconfig.json中添加的"clients"类型配置实际无效。

解决方案

  • 安装Chrome扩展类型依赖
    首先安装官方维护的Chrome扩展类型定义包,这是识别Chrome扩展API类型的核心:

    npm install @types/chrome --save-dev
    
  • 修正tsconfig.json配置
    在compilerOptions.types中替换为"chrome",移除无效的"clients"配置:

    {
      "compilerOptions": {
        "types": ["chrome"]
      }
    }
    
  • 改用self.clients显式访问
    若上述配置后仍有问题,可通过self对象(Service Worker的全局作用域)访问clients,TypeScript对self的类型识别更友好:

    async function hasOffscreenDocument(path: string) {
      const offscreenUrl = chrome.runtime.getURL(path);
      const matchedClients = await self.clients.matchAll();
      for (const client of matchedClients) {
        if (client.url === offscreenUrl) {
          return true;
        }
      }
      return false;
    }
    
  • 手动声明全局类型(兜底方案)
    如果仍未解决,可在代码顶部手动声明clients全局变量:

    declare const clients: Clients;
    
    async function hasOffscreenDocument(path: string) {
      // 原有逻辑代码
      const offscreenUrl = chrome.runtime.getURL(path);
      const matchedClients = await clients.matchAll();
      for (const client of matchedClients) {
        if (client.url === offscreenUrl) {
          return true;
        }
      }
      return false;
    }
    

内容的提问来源于stack exchange,提问作者Mihai Marinescu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 01:27:08