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

Chrome扩展i18n能否自定义设置当前locale以获取指定语言文本?

Chrome扩展i18n适配站点语言实现方案

Chrome扩展提供的chrome.i18n.getMessage()接口默认仅返回浏览器当前语言对应的翻译文本,不支持传入自定义locale参数,无法直接匹配当前访问站点的语言,可通过以下方案实现需求:

实现步骤

  • 预加载全量翻译资源
    扩展初始化阶段主动拉取_locales目录下所有支持语种的messages.json文件,缓存到全局对象或扩展存储中:
    // 自定义支持的语种列表
    const SUPPORTED_LOCALES = ['zh-CN', 'en', 'ja']
    const i18nCache = {}
    
    async function preloadI18n() {
      for (const locale of SUPPORTED_LOCALES) {
        const res = await fetch(chrome.runtime.getURL(`_locales/${locale}/messages.json`))
        i18nCache[locale] = await res.json()
      }
    }
    
  • 封装自定义翻译方法
    实现支持传入自定义locale参数的翻译方法,逻辑和官方getMessage对齐,支持占位符替换:
    function getCustomMessage(messageName, targetLocale, placeholders = []) {
      // 优先级:指定语种 > 浏览器默认语种 > 兜底英文
      const messages = i18nCache[targetLocale] || i18nCache[chrome.i18n.getUILanguage()] || i18nCache['en']
      const message = messages[messageName]?.message
      if (!message) return messageName
      // 兼容官方$1、$2格式的占位符逻辑
      return message.replace(/\$(\d+)/g, (match, index) => placeholders[Number(index) - 1] || match)
    }
    
  • 按需调用匹配站点语言
    拿到站点语言后,直接调用自定义方法传入对应locale参数即可获取对应语种的翻译文本:
    // siteLocale为你获取到的当前站点语言
    const tipText = getCustomMessage('operation_tip', siteLocale, ['测试参数'])
    

额外说明

  • 多场景共用翻译资源时,可将缓存的翻译内容存入chrome.storage.local,避免popup、background、content script重复加载资源。
  • 站点语言不在支持列表时,可自行调整降级逻辑,适配你的业务需求。
  • 该方案完全兼容Chrome扩展官方的i18n文件规范,无需调整现有翻译文件的存储格式和维护方式。

内容的提问来源于stack exchange,提问作者Felipe Lopez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:15:03