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

Chrome扩展注入脚本:如何避免用any定义函数与参数类型?

类型安全的Chrome扩展脚本注入实现方案

问题根源在于Chrome的chrome.scripting.executeScript类型定义与你的泛型参数不兼容——默认func类型为Function、args为unknown[],TypeScript无法自动推断它们和指定函数的类型关联。以下是完全避免any的类型安全实现:

type InjectableFunction = typeof getPageInfo | typeof setPercen;

async function injectScriptToPage<F extends InjectableFunction>(
  func: F,
  args: Parameters<F>
): Promise<ReturnType<F> | undefined> {
  if (actTab.id === undefined) {
    console.log("vacio tab id");
    return;
  }

  // 类型断言告知TypeScript:我们已确保func和args的类型匹配API要求
  const pr = await chrome.scripting.executeScript({
    target: { tabId: actTab.id },
    func: func as (...args: unknown[]) => ReturnType<F>,
    args: args as unknown[],
  });

  const result = pr?.[0]?.result as ReturnType<F>;
  if (result === undefined) {
    console.log("vacio result");
    return;
  }

  // 保留你的业务类型检查逻辑
  if (!("titulo" in result) && !("currentTime" in result)) {
    console.log("Err no es ni refresh ni once");
  }

  return result;
}

关键细节说明

  • 类型绑定:通过Parameters<F>和ReturnType<F>分别绑定入参和返回值的类型,严格限制传入函数的合法性。
  • 安全断言:对func和args的类型断言是必要的——Chrome API要求参数为unknown[],但我们已经在外部通过泛型确保了类型匹配,因此断言是安全的。
  • 函数约束:注入的函数必须是无外部依赖的纯函数,不能引用闭包变量(比如getPageInfo或setPercen内部不能使用actTab这类外部变量),否则Chrome会抛出序列化错误。

贴合业务返回类型的调整

如果你的dataPageU是dataPage | void的联合类型,可以将返回类型直接替换为Promise<dataPageU>:

async function injectScriptToPage<F extends InjectableFunction>(
  func: F,
  args: Parameters<F>
): Promise<dataPageU> {
  // 内部逻辑不变,最后返回result as dataPageU
}

内容的提问来源于stack exchange,提问作者Sr.Jose

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:12:50