> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/tech/maiagent-tech-ja/api-integration/web-chat-sdk.md).

# Web Chat SDK 操作コマンド

MaiAgent SDK は、開発者が MaiAgent チャットボットを任意の Web サイトに簡単に統合できるよう、包括的な JavaScript API を提供しています。

## **一、初期化について**

{% hint style="info" %}
埋め込みスクリプトの取得方法については、[🌐対話プラットフォームの連携：Web サイト](https://docs.maiagent.ai/release/website) をご参照ください。

この手順に従って操作すると、スクリプトに webChatId パラメータが自動的に付与されます。
{% endhint %}

埋め込みスクリプトの読み込み後、システムは自動的に `document.body.onload` イベントハンドラーを登録して Web Chat の初期化を実行するため、手動で登録を呼び出す必要はありません。初期化のタイミングを制御したい場合（たとえば他のリソースの読み込み完了を待つ、またはレンダリングを遅延させる場合）は、以下の方法を利用できます。

1. **スクリプトの遅延読み込み**：`embed.min.js` の読み込みタイミングを制御します
2. **手動での初期化トリガー**：適切なタイミングで `document.body.onload()` メソッドを呼び出します

この仕組みにより、開発者は DOM レンダリングと Web Chat の初期化を分離でき、より柔軟な統合方法を実現できます。

#### 注意事項

* システムは連絡先 API を通じて Contact ID が付与されたことを確認した後に初期化を行います。
* Query Metadata を利用することで、Web Chat の初期化時点で[ナレッジマネジメント権限](/tech/maiagent-tech-ja/authorization-integration/zhi-shi-guan-li-quan-xian-query-metadata-cha-xun-yuan-zi-liao-zong-lan/json-interfaces.md#webchat-chu-shi-hua-she-ding)を付与できます

ナレッジマネジメント権限の詳細については、[🌐ナレッジマネジメント権限（Query Metadata / メタデータ照会）概要↗](/tech/maiagent-tech-ja/authorization-integration/zhi-shi-guan-li-quan-xian-query-metadata-cha-xun-yuan-zi-liao-zong-lan.md)をご参照ください。

## 二、クイックスタート

### 1. SDK の読み込み

```html
<script>
  window.maiagentChatbotConfig = {
    webChatId: 'your-web-chat-id',
    baseUrl: '<https://yourdomain.com/web-chats>',
    primaryColor: '#1890ff',
    allowDrag: true,
  }
</script>
<script src="<https://yourdomain.com/js/embed.min.js>"></script>

```

### 2. API の使用

```jsx
// SDK の初期化完了を待つ
document.addEventListener('DOMContentLoaded', () => {
  // メッセージ返信を監視
  MaiAgent.events.on('messageReply', (data) => {
    console.log('新しいメッセージを受信:', data)
  })

  // メッセージを送信
  MaiAgent.chat.send('こんにちは！')

  // チャットウィンドウを開く
  MaiAgent.control.open()
})

```

## 三、基本設定

SDK を読み込む前に、まず `maiagentChatbotConfig` オブジェクトを設定する必要があります。

{% hint style="info" %}
詳細なパラメータの説明については、下記の [設定オプション](#si-pei-zhi-xuan-xiang) をご参照ください。
{% endhint %}

```jsx
window.maiagentChatbotConfig = {
  webChatId: 'your-web-chat-id', // 必須：チャットボット ID
  baseUrl: '<https://yourdomain.com/web-chats>', // 必須：API ベース URL
  primaryColor: '#1890ff', // テーマカラー
  allowDrag: true, // ボタンのドラッグを許可するか
  buttonSize: '48', // ボタンのサイズ（ピクセル）
  buttonRadius: '50%', // ボタンの角丸
  buttonPositionBottom: '16', // ボタンの下端からの距離
  buttonPositionRight: '16', // ボタンの右端からの距離
  windowWidth: '24rem', // チャットウィンドウの幅
  windowHeight: '40rem', // チャットウィンドウの高さ
  windowRadius: '0.75rem', // チャットウィンドウの角丸
  windowPositionBottom: '5rem', // チャットウィンドウの下端からの距離
  windowPositionRight: '1rem', // チャットウィンドウの右端からの距離
  boxShadow: '0.125rem 0.125rem 0.5rem #00000044', // 影の効果
  contactId: 'contact-id', // 任意：連絡先 ID
  queryMetadata: { key: 'value' }, // 任意：照会メタデータ
  closeIconHtml: '<svg>...</svg>', // 任意：カスタム閉じるアイコン
  openIconHtml: '<svg>...</svg>' // 任意：カスタム開くアイコン
}

```

## 四、API 機能

### 1. チャット制御

#### `MaiAgent.control.open()`

チャットウィンドウを開きます

```jsx
// チャットウィンドウを開く
MaiAgent.control.open()

```

#### `MaiAgent.control.close()`

チャットウィンドウを閉じます

```jsx
// チャットウィンドウを閉じる
MaiAgent.control.close()

```

#### `MaiAgent.control.isOpen()`

チャットウィンドウが開いているかを確認します

```jsx
// チャットウィンドウの状態を確認
const isOpen = MaiAgent.control.isOpen()
console.log('チャットウィンドウの状態:', isOpen ? '開いている' : '閉じている')

```

### 2. メッセージ管理

#### `MaiAgent.chat.send(content)`

チャットボットにメッセージを送信します

```jsx
// シンプルなテキストメッセージを送信
MaiAgent.chat.send('こんにちは、サポートが必要です')

```

#### `MaiAgent.chat.clearHistory()`

チャット履歴を消去します

```jsx
// すべてのチャット履歴を消去
MaiAgent.chat.clearHistory()

```

#### `MaiAgent.chat.newConversation()`

新しい会話を開始します

```jsx
// 新しい会話を開始
MaiAgent.chat.newConversation()

```

### 3. イベント監視

#### `MaiAgent.events.on(eventType, callback)`

イベントリスナーを登録します

```jsx
// メッセージ返信を監視 - 文字列を使用
MaiAgent.events.on('messageReply', (data) => {
  console.log('返信を受信:', data)
  // data にはメッセージ内容、タイムスタンプなどの情報が含まれます
})

// または EVENT_TYPES 定数を使用（本番環境での使用を推奨）
MaiAgent.events.on(MaiAgent.EVENT_TYPES.MESSAGE_REPLY, (data) => {
  console.log('返信を受信:', data)
})

```

#### `MaiAgent.events.off(eventType, callback)`

イベントリスナーを削除します

```jsx
// 特定のイベントリスナーを削除
function messageHandler(data) {
  console.log('メッセージイベント:', data)
}

MaiAgent.events.on('messageReply', messageHandler)
// ... 後で削除
MaiAgent.events.off('messageReply', messageHandler)

```

### 4. 言語設定

**Web Chat の言語と音声制御**

{% hint style="info" %}
MaiAgent の対応言語については、[多言語対応](https://docs.maiagent.ai/build/multi-language-support) をご参照ください。
{% endhint %}

* Web Chat は繁体字中国語、簡体字中国語、英語、日本語、韓国語、タイ語など多言語に対応しており、今後も継続的に拡充していきます
* 埋め込み後は globalThis.MaiAgent オブジェクトへグローバルにアクセスでき、テキストまたは音声の言語を設定できます
* 「繁体字中国語」および「簡体字中国語」以外の言語については、「言語コード」を指定するだけで設定できます

**言語設定の例**

Web サイトのニーズに応じて、異なる言語インターフェースや音声オプションを設定できます。

* テキストインターフェース：繁体字中国語（zh-TW）、簡体字中国語（zh-CN）、英語（en）などに設定できます
* 音声設定：ASR（音声認識）および TTS（音声合成）で使用する言語を設定できます

#### `MaiAgent.speech.set(lang, provider)`

音声の言語とプロバイダーを設定します

```jsx
// 音声を中国語に設定し、Azure プロバイダーを使用
MaiAgent.speech.set('zh-TW', 'azure')

// 音声を英語に設定し、デフォルトのプロバイダーを使用
MaiAgent.speech.set('en-US')

```

#### `MaiAgent.locale.set(lang)`

インターフェースの言語を設定します

```jsx
// 繁体字中国語に設定
MaiAgent.locale.set('zh-TW')

// 簡体字中国語に設定
MaiAgent.locale.set('zh-CN')

// 英語に設定
MaiAgent.locale.set('en')

```

## 五、設定オプション

### 1. 基本設定

| オプション           | 型             | 必須  | デフォルト値 | 説明               |
| --------------- | ------------- | --- | ------ | ---------------- |
| `webChatId`     | string        | はい  | -      | チャットボットの一意の識別子   |
| `baseUrl`       | string        | はい  | -      | API サービスのベース URL |
| `contactId`     | string        | いいえ | -      | 連絡先識別子           |
| `queryMetadata` | object/string | いいえ | -      | 追加の照会メタデータ       |

### 2. 外観設定

| オプション          | 型      | デフォルト値                               | 説明            |
| -------------- | ------ | ------------------------------------ | ------------- |
| `primaryColor` | string | `#1890ff`                            | テーマカラー        |
| `buttonSize`   | string | `48`                                 | ボタンのサイズ（ピクセル） |
| `buttonRadius` | string | `50%`                                | ボタンの角丸        |
| `windowWidth`  | string | `24rem`                              | チャットウィンドウの幅   |
| `windowHeight` | string | `40rem`                              | チャットウィンドウの高さ  |
| `windowRadius` | string | `0.75rem`                            | チャットウィンドウの角丸  |
| `boxShadow`    | string | `0.125rem 0.125rem 0.5rem #00000044` | 影の効果          |

### 3. 位置設定

| オプション                  | 型      | デフォルト値 | 説明                |
| ---------------------- | ------ | ------ | ----------------- |
| `buttonPositionBottom` | string | `16`   | ボタンの下端からの距離（ピクセル） |
| `buttonPositionRight`  | string | `16`   | ボタンの右端からの距離（ピクセル） |
| `windowPositionBottom` | string | `5rem` | チャットウィンドウの下端からの距離 |
| `windowPositionRight`  | string | `1rem` | チャットウィンドウの右端からの距離 |

### 4. 動作設定

| オプション       | 型       | デフォルト値 | 説明                 |
| ----------- | ------- | ------ | ------------------ |
| `allowDrag` | boolean | `true` | チャットボタンのドラッグを許可するか |

#### 5. カスタムアイコン

| オプション           | 型      | デフォルト値    | 説明                |
| --------------- | ------ | --------- | ----------------- |
| `closeIconHtml` | string | デフォルト SVG | カスタム閉じるアイコンの HTML |
| `openIconHtml`  | string | デフォルト SVG | カスタム開くアイコンの HTML  |

## 六、イベントタイプ

### 1. 監視可能なイベント

| イベント名          | 説明                   | データ形式                                         |
| -------------- | -------------------- | --------------------------------------------- |
| `messageReply` | チャットボットの返信を受信したときに発火 | `{ content: string, timestamp: number, ... }` |

### 2. 内部イベント（参考）

| イベント名               | 説明            |
| ------------------- | ------------- |
| `setSpeechLanguage` | 音声言語を設定       |
| `setLocale`         | インターフェース言語を設定 |
| `sendMessage`       | メッセージを送信      |
| `clearHistory`      | 履歴を消去         |
| `newConversation`   | 新しい会話を開始      |
| `closeBubbleWindow` | チャットウィンドウを閉じる |
| `sdkReady`          | SDK 準備完了      |

## 七、完全なサンプル

以下は、完全な統合サンプルです。

```html
<!doctype html>
<html lang="zh-TW">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>MaiAgent SDK 統合サンプル</title>
  </head>
  <body>
    <h1>私の Web サイト</h1>
    <p>ここは Web サイトのコンテンツです...</p>

    <!-- いくつかのインタラクションボタン -->
    <button onclick="openChatBot()">カスタマーサポートを開く</button>
    <button onclick="sendWelcomeMessage()">ウェルカムメッセージを送信</button>
    <button onclick="clearChatHistory()">会話を消去</button>
    <button onclick="startNewChat()">新しい会話</button>

    <!-- MaiAgent SDK 設定 -->
    <script>
      window.maiagentChatbotConfig = {
        webChatId: 'your-web-chat-id',
        baseUrl: '<https://your-domain.com/web-chats>',
        primaryColor: '#007bff',
        allowDrag: true,
        buttonSize: '56',
        buttonRadius: '50%',
        windowWidth: '28rem',
        windowHeight: '45rem',
        contactId: 'website-visitor',
        queryMetadata: {
          source: 'website',
          page: window.location.pathname,
        },
      }
    </script>

    <!-- MaiAgent SDK の読み込み -->
    <script src="<https://your-domain.com/js/embed.min.js>"></script>

    <!-- アプリケーションロジック -->
    <script>
      // DOM と SDK の読み込み完了を待つ
      document.addEventListener('DOMContentLoaded', function () {
        // イベントリスナーを設定
        setupEventListeners()

        // 言語を設定
        MaiAgent.locale.set('zh-TW')
        MaiAgent.speech.set('zh-TW', 'azure')

        console.log('MaiAgent SDK の準備が完了しました')
      })

      function setupEventListeners() {
        // メッセージ返信を監視
        MaiAgent.events.on('messageReply', function (data) {
          console.log('ボットの返信を受信:', data)

          // ここで返信を処理できます。例：
          // - 受信した data は JSON のため、JSON.parse(data) する必要があります
          // - 分析データを記録
          // - UI の状態を更新
          // - その他のビジネスロジックを発火
        })
      }

      // インタラクション関数
      function openChatBot() {
        MaiAgent.control.open()
      }

      function closeChatBot() {
        MaiAgent.control.close()
      }

      function sendWelcomeMessage() {
        MaiAgent.chat.send('こんにちは！サービスについて知りたいです')

        // チャットウィンドウが開いていることを確認
        MaiAgent.control.open()
      }

      function clearChatHistory() {
        if (confirm('すべての会話履歴を消去してもよろしいですか？')) {
          MaiAgent.chat.clearHistory()
          console.log('会話履歴を消去しました')
        }
      }

      function startNewChat() {
        MaiAgent.chat.newConversation()
        MaiAgent.control.open()
        console.log('新しい会話を開始しました')
      }

      // ページの表示状態の変化を監視し、ユーザーがページに戻ったときにメッセージを送信できます
      document.addEventListener('visibilitychange', function () {
        if (!document.hidden && MaiAgent.control.isOpen()) {
          console.log('ユーザーがページに戻りました。チャットウィンドウは開いたままです')
          // ここで何らかの操作を実行できます
        }
      })
    </script>
  </body>
</html>

```

## 八、応用的な使用テクニック

### 1. 動的な設定更新

```jsx
// テーマカラーを動的に更新
function updateTheme(color) {
  // 注意：反映させるには再初期化が必要です
  window.maiagentChatbotConfig.primaryColor = color
  initializeChatbot()
  // SDK を再読み込みするか、ページを再読み込み
}

```

### 2. エラー処理

```jsx
// SDK が利用可能かを確認
function checkSDKAvailability() {
  if (typeof MaiAgent === 'undefined') {
    console.error('MaiAgent SDK が読み込まれていません')
    return false
  }

  if (!MaiAgent.control) {
    console.error('MaiAgent SDK が完全に初期化されていません')
    return false
  }

  return true
}

// 安全に SDK を使用
function safeOpenChat() {
  if (checkSDKAvailability()) {
    MaiAgent.control.open()
  }
  else {
    alert('チャットサービスは一時的にご利用いただけません。しばらくしてから再度お試しください')
  }
}

```

### 3. 他のシステムとの統合

```jsx
// Google Analytics との統合
MaiAgent.events.on('messageReply', (data) => {
  // チャットのインタラクションイベントを記録
  if (typeof gtag !== 'undefined') {
    gtag('event', 'chat_interaction', {
      event_category: 'engagement',
      event_label: 'bot_reply',
      value: 1
    })
  }
})

```

## 九、トラブルシューティング

### 1. よくある問題

1. **SDK が読み込まれない**
   * `maiagentChatbotConfig` が SDK スクリプトより前に定義されているか確認してください
   * ネットワーク接続とスクリプト URL が正しいか確認してください
2. **チャットウィンドウが開かない**
   * `webChatId` と `baseUrl` の設定が正しいか確認してください
   * ブラウザのコンソールにエラーメッセージがないか確認してください
3. **イベントリスナーが機能しない**
   * DOM の読み込み完了後にイベントリスナーを登録しているか確認してください
   * イベント名が正しいか確認してください
4. **ボタンの位置が異常**
   * CSS の競合を確認してください
   * 位置パラメータの形式が正しいか確認してください


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.maiagent.ai/tech/maiagent-tech-ja/api-integration/web-chat-sdk.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
