如何从Service Worker关闭Chrome扩展弹窗?遇TS类型报错求助
chrome.runtime.getContexts的TSlint报错问题 问题描述
尝试使用chrome.extension.getViews从Service Worker关闭Chrome扩展弹窗时,出现TypeError: chrome.extension.getViews is not a function错误。已知Chrome扩展V3版本中该API已替换为chrome.runtime.getContexts,且官方文档有定义,但代码中使用时TSlint提示Property getContexts does not exist on type typeof runtime。附带tsconfig.json配置如下:
{ "compilerOptions": { "target": "es6", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "Node16", "moduleResolution": "Node16", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": [ "src" ] }
原因分析
这并非TypeScript本身的问题,而是Chrome扩展的TypeScript类型定义包未包含chrome.runtime.getContexts的声明导致的。该API是Manifest V3新增的功能,如果使用的@types/chrome包版本较旧,就会缺少对应的类型定义,从而触发TSlint报错。
解决方法
更新
@types/chrome包
执行以下命令更新到最新版本,确保类型定义包含新增的API:npm update @types/chrome --save-dev若未安装过该包,先执行安装命令:
npm install @types/chrome --save-dev检查tsconfig.json类型配置
确认tsconfig.json的compilerOptions.types字段中包含chrome(如果配置了该字段),确保TypeScript能加载Chrome扩展的类型定义:"compilerOptions": { // 其他现有配置... "types": ["chrome"] }若未设置
types字段,默认会自动加载所有@types下的包,无需额外配置。临时跳过类型检查(不推荐长期使用)
若更新包后仍有问题,可在代码行前添加注释临时跳过类型检查:// @ts-ignore chrome.runtime.getContexts({contextTypes: ["POPUP"]}).then(contexts => { contexts.forEach(ctx => ctx.window?.close()); });手动补充类型声明
如果最新版@types/chrome仍未包含该API的定义,可在项目中创建自定义类型文件(如chrome.d.ts),补充如下声明:declare namespace chrome.runtime { interface ContextFilter { contextTypes?: string[]; contextIds?: number[]; } interface Context { window: Window; // 可根据需要添加其他属性 } function getContexts(filter?: ContextFilter): Promise<Context[]>; }确保该文件被包含在
tsconfig.json的include数组中。
内容的提问来源于stack exchange,提问作者syydi

