国際化

Addfox は Chrome 拡張機能標準の _locales ディレクトリを介した国際化をサポートします。

ディレクトリ構造

public/ ディレクトリに _locales を作成:

public
_locales
en
messages.json
zh_CN
messages.json
ja
messages.json

メッセージファイル形式

messages.json 形式:

{
  "appName": {
    "message": "My Extension",
    "description": "The name of the extension"
  },
  "appDescription": {
    "message": "A great browser extension",
    "description": "The description of the extension"
  },
  "welcomeMessage": {
    "message": "Welcome, $USER$!",
    "description": "Welcome message with user name",
    "placeholders": {
      "user": {
        "content": "$1",
        "example": "John"
      }
    }
  }
}

Manifest での使用

{
  "name": "__MSG_appName__",
  "description": "__MSG_appDescription__",
  "default_locale": "zh_CN"
}

コードでの使用

JavaScript/TypeScript

// 現在の言語のメッセージを取得
const message = chrome.i18n.getMessage("welcomeMessage", ["John"]);
console.log(message); // "Welcome, John!"

Vue

<template>
  <h1>{{ t('appName') }}</h1>
  <p>{{ t('welcomeMessage', ['John']) }}</p>
</template>

<script setup>
// i18n ユーティリティ関数をカプセル化
const t = (key, args) => chrome.i18n.getMessage(key, args);
</script>

React

// utils/i18n.ts
export const t = (key: string, args?: string[]): string => {
  return chrome.i18n.getMessage(key, args);
};

// app/popup/App.tsx
import { t } from "@/utils/i18n";

export function App() {
  return (
    <div>
      <h1>{t("appName")}</h1>
      <p>{t("welcomeMessage", ["John"])}</p>
    </div>
  );
}

ユーザーの言語を検出

// ブラウザの現在の言語を取得
const currentLocale = chrome.i18n.getUILanguage();
console.log(currentLocale); // "zh-CN", "en", など

// すべてのサポートされている言語を取得
const locales = chrome.i18n.getAcceptLanguages();
locales.then(languages => console.log(languages));

完全な例

中国語メッセージファイル

// public/_locales/zh_CN/messages.json
{
  "appName": {
    "message": "タブマネージャー",
    "description": "拡張機能名"
  },
  "appDescription": {
    "message": "ブラウザタブを効率的に管理",
    "description": "拡張機能の説明"
  },
  "tabCount": {
    "message": "$COUNT$ 個のタブがあります",
    "description": "タブ数を表示",
    "placeholders": {
      "count": {
        "content": "$1",
        "example": "5"
      }
    }
  }
}

英語メッセージファイル

// public/_locales/en/messages.json
{
  "appName": {
    "message": "Tab Manager",
    "description": "Extension name"
  },
  "appDescription": {
    "message": "Manage your browser tabs efficiently",
    "description": "Extension description"
  },
  "tabCount": {
    "message": "You have $COUNT$ tabs",
    "description": "Show tab count",
    "placeholders": {
      "count": {
        "content": "$1",
        "example": "5"
      }
    }
  }
}

言語コード

よく使用される言語コード:

言語コード
簡体字中国語zh_CN
繁体字中国語zh_TW
英語en
日本語ja
韓国語ko
ドイツ語de
フランス語fr
スペイン語es

完全なリストは Chrome 拡張機能ドキュメント を参照してください。

注意事項

  • manifest の default_locale は必ず指定する必要がある
  • すべてのメッセージファイルには default_locale で指定された言語を含める必要がある
  • プレースホルダーは $1, $2 などを使用して表し、getMessage の2番目のパラメータ配列に対応する

関連リンク