> For the complete documentation index, see [llms.txt](https://gitbook.com/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.com/docs/documentation/ja-gitbook-documentation/gong-kai/embedding/implementation/nodejs.md).

# Node.js/NPM

より細かい制御が必要で、アプリケーションレベルで作業したい場合は、npm から GitBook の embed パッケージをインストールできます。この方法は、サーバーサイドレンダリング、ビルド時統合、またはカスタム iframe 管理に最適です。

## 手順

{% stepper %}
{% step %}
**パッケージをインストールする**

追加 `@gitbook/embed` をプロジェクトに:

```bash
npm install @gitbook/embed
```

完全な API リファレンスとソースコードについては、 [`@gitbook/embed` GitHub 上のパッケージを参照してください](https://github.com/GitbookIO/gitbook/tree/main/packages/embed).
{% endstep %}

{% step %}
**パッケージをインポートする**

アプリケーションコードで、 `createGitBook` 関数をインポートします:

```javascript
import { createGitBook } from "@gitbook/embed";
```

または CommonJS を使用する場合:

```javascript
const { createGitBook } = require("@gitbook/embed");
```

{% endstep %}

{% step %}
**GitBook を初期化する**

ドキュメントサイトの URL で GitBook インスタンスを作成します:

```javascript
const gitbook = createGitBook({
  siteURL: "https://docs.company.com",
});
```

{% endstep %}

{% step %}
**iframe を作成する**

iframe 要素を生成し、そのソースを埋め込み URL に設定します:

```javascript
const iframe = document.createElement("iframe");
iframe.src = gitbook.getFrameURL({
  visitor: {
    token: 'your-jwt-token', // 任意: Adaptive Content または認証済みアクセス用
    unsignedClaims: { // 任意: 動的式向けのカスタムクレーム
      userId: '123',
      plan: 'premium'
    }
  }
});
iframe.id = "gitbook-embed-container";
iframe.style.border = "none";
iframe.style.width = "100%";
iframe.style.height = "600px";
iframe.allow = "clipboard-write";
```

{% hint style="info" %}
Assistant タブを使用する場合は、iframe に `allow="clipboard-write"` を設定してください。NPM パッケージでは iframe の設定はユーザー側で行います。スタンドアロンの [Script tag](/docs/documentation/ja-gitbook-documentation/gong-kai/embedding/implementation/script.md) 実装ではこれが自動で追加されます。
{% endhint %}
{% endstep %}

{% step %}
**フレームを追加する**

GitBook フレームインスタンスを作成し、ページにマウントします:

```javascript
const frame = gitbook.createFrame(iframe);
document.getElementById("gitbook-embed-container").appendChild(iframe);
```

{% endstep %}

{% step %}
**埋め込みをプログラムで制御する**

フレームインスタンスを使って埋め込みとやり取りします:

```javascript
// docs タブの特定のページに移動
frame.navigateToPage("/getting-started");

// アシスタントタブに切り替え
frame.navigateToAssistant();

// チャットにメッセージを送信
frame.postUserMessage("How do I get started?");

// チャット履歴をクリア
frame.clearChat();
```

{% endstep %}

{% step %}
**埋め込みを設定する**

カスタマイズオプションで埋め込みを設定します:

```javascript
frame.configure({
  trademark: false,
  tabs: ['assistant', 'search', 'docs'],
  actions: [
    {
      icon: 'circle-question',
      label: 'サポートに連絡',
      onClick: () => window.open('https://support.example.com', '_blank')
    }
  ],
  greeting: { title: 'ようこそ！', subtitle: 'どのようにお手伝いできますか？' },
  assistantName: 'Support Copilot',
  closeButton: true,
  suggestions: ['GitBook とは何ですか？', 'どう始めればよいですか？'],
  tools: [/* ... */]
});
```

{% endstep %}

{% step %}
**イベントを監視する**

埋め込みイベントに応答するためにイベントリスナーを登録します:

```javascript
frame.on('close', () => {
  console.log('Frame closed');
});

// 完了したら購読解除
const unsubscribe = frame.on('navigate', (data) => {
  console.log('遷移先:', data.path);
});
```

{% endstep %}
{% endstepper %}

## API リファレンス

### クライアントファクトリー

* `createGitBook(options: { siteURL: string })` → `GitBookClient`
* `client.getFrameURL(options?: { visitor?: {...}, colorScheme?: 'light' | 'dark' })` → `string` - 任意のフレームオプション付きで iframe の URL を取得する
* `client.createFrame(iframe: HTMLIFrameElement)` → `GitBookFrameClient` - iframe と通信するためのフレームクライアントを作成する

### フレームクライアントのメソッド

* `frame.navigateToPage(path: string)` → `void` - docs タブの特定のページに移動する
* `frame.navigateToAssistant()` → `void` - Assistant タブに切り替える
* `frame.postUserMessage(message: string)` → `void` - チャットにメッセージを送信する
* `frame.clearChat()` → `void` - チャット履歴をクリアする
* `frame.configure(settings: Partial<GitBookEmbeddableConfiguration>)` → `void` - 埋め込みを設定する
* `frame.on(event: string, listener: Function)` → `() => void` - イベントリスナーを登録する（unsubscribe 関数を返す）

## 設定オプション

ほとんどのカスタマイズオプションは `frame.configure({...})`.

#### `tabs`

で利用できます。表示するタブを上書きします。

検索はデフォルトで有効です。 `tabs`を設定すると、埋め込みには指定したタブのみが表示されます。

* **種類**: `('assistant' | 'search' | 'docs')[]`

#### `actions`

タブと並んでサイドバーに表示されるカスタムアクションボタン。各アクションボタンは、クリック時にコールバックを実行します。

**注意**: これは以前は `buttons`と呼ばれていました。 `actions` を使用してください。

* **種類**: `Array<{ icon: string, label: string, onClick: () => void }>`

#### `greeting`

Assistant タブに表示されるウェルカムメッセージ。

* **種類**: `{ title: string, subtitle: string }`

#### `assistantName`

UI に表示される Assistant 名を上書きします。

* **種類**: `string`
* **最大長**: `32` 文字

#### `closeButton`

Assistant 内に閉じるボタンを表示します。

* **種類**: `boolean`

#### `suggestions`

Assistant のウェルカム画面に表示されるおすすめの質問。

* **種類**: `string[]`

#### `trademark`

Docs Embed のフッターや Assistant のブランド表示を含め、埋め込み UI 内で GitBook の商標を表示または非表示にします。

* **種類**: `boolean`
* **既定**: `true`

#### `tools`

Assistant を拡張するためのカスタム AI ツール。詳細は [カスタムツールの作成](/docs/documentation/ja-gitbook-documentation/gong-kai/embedding/configuration/creating-custom-tools.md) をご覧ください。

* **種類**: `Array<{ name: string, description: string, inputSchema: object, execute: Function, confirmation?: {...} }>`

### フレーム URL のオプション

一部のオプションは `getFrameURL({...})`.

#### `colorScheme`

に渡されます。埋め込みの配色を上書きします。

省略した場合、埋め込みは iframe の CSS に従い、 `color-scheme`親ページまたはブラウザの設定を継承できます。

* **種類**: `'light' | 'dark'`

### `visitor` (認証済みアクセス)

次に渡します `getFrameURL({ visitor: {...} })`。用途は [Adaptive Content](/docs/documentation/ja-gitbook-documentation/gong-kai/adaptive-content.md) 、 [認証済みアクセス](/docs/documentation/ja-gitbook-documentation/gong-kai/site-audience/authenticated-access.md).

* **種類**: `{ token?: string, unsignedClaims?: Record<string, unknown> }`

## よくある落とし穴

* **パッケージのインストールを忘れる** – 実行してください `npm install @gitbook/embed` をインポートする前に。
* **siteURL がない** – `siteURL` オプションは必須で、公開済みのドキュメントサイトと一致している必要があります。
* **iFrame が表示されない** – 親コンテナに iframe を表示するのに十分な幅/高さがあることを確認してください。
* **初期化前に呼び出された Frame メソッド** – `createFrame()` が完了してから frame メソッドを呼び出してください。
* **イベントの購読解除をしていない** – `frame.on()` から返される unsubscribe 関数を必ず呼び出して、メモリリークを防いでください。
* **古い API メソッドを使用している** – `open()`, `close()`, `toggle()`、および `destroy()` は NPM パッケージでは利用できません。代わりに frame client のメソッドを使用してください。


---

# 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://gitbook.com/docs/documentation/ja-gitbook-documentation/gong-kai/embedding/implementation/nodejs.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.
