> 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/publish/embedding/implementation/nodejs.md).

# Node.js/NPM

NPM パッケージを使って Docs Embed を統合し、アプリケーション全体を細かく制御します

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

## 手順

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

プロジェクトに `@gitbook/embed` を追加します。

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

API リファレンスとソースコードの詳細については、GitHub の [`@gitbook/embed` パッケージを参照してください](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 の設定は行われないため、ご自身で設定する必要があります。スタンドアロンの [スクリプトタグ](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/embedding/implementation/script.md) による実装では、この設定が自動的に追加されます。
{% endhint %}
{% endstep %}

{% step %}
**フレームを取り付ける**

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

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

{% endstep %}

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

フレームのインスタンスを使用して、埋め込みを操作します。

```javascript
// ドキュメントタブで特定のページに移動
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: 'Contact Support',
      onClick: () => window.open('https://support.example.com', '_blank')
    }
  ],
  greeting: { title: 'Welcome!', subtitle: 'How can I help?' },
  assistantName: 'Support Copilot',
  closeButton: true,
  suggestions: ['What is GitBook?', 'How do I get started?'],
  tools: [/* ... */]
});
```

{% endstep %}

{% step %}
**イベントをリッスンする**

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

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

// 完了したら登録を解除
const unsubscribe = frame.on('navigate', (data) => {
  console.log('Navigated to:', 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` - ドキュメントタブで指定したページに移動します
* `frame.navigateToAssistant()` → `void` - アシスタントタブに切り替えます
* `frame.postUserMessage(message: string)` → `void` - チャットにメッセージを投稿します
* `frame.clearChat()` → `void` - チャット履歴を消去します
* `frame.configure(settings: Partial<GitBookEmbeddableConfiguration>)` → `void` - 埋め込みを設定します
* `frame.on(event: string, listener: Function)` → `() => void` - イベントリスナーを登録します（登録解除関数を返します）

## 設定オプション

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

#### `tabs`

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

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

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

#### `actions`

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

**注**：以前は `buttons`が使われていました。代わりに `actions` を使用してください。

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

#### `greeting`

アシスタントタブに表示されるウェルカムメッセージ。

* **型**: `{ title: string, subtitle: string }`

#### `assistantName`

UI に表示されるアシスタント名を上書きします。

* **型**: `string`
* **最大文字数**: `32` 文字

#### `closeButton`

アシスタント内に閉じるボタンを表示します。

* **型**: `boolean`

#### `suggestions`

アシスタントのウェルカム画面に表示される提案質問。

* **型**: `string[]`

#### `trademark`

Docs Embed フッターやアシスタントのブランディングを含む、埋め込み UI 内の GitBook 商標の表示/非表示を切り替えます。

* **型**: `boolean`
* **デフォルト**: `true`

#### `tools`

Assistant を拡張するカスタム AI ツールです。詳しくは [カスタムツールの作成](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/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: {...} })`に渡します。これは [適応型コンテンツ](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/adaptive-content.md) および [認証済みアクセス](https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/site-audience/authenticated-access.md).

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

## よくある落とし穴

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


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://gitbook.com/docs/documentation/ja-gitbook-documentation/publish/embedding/implementation/nodejs.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
