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

# Node.js/NPM

より細かい制御が必要で、アプリケーションレベルで作業したい場合は、npm から GitBook の埋め込みパッケージをインストールできます。この方法は、サーバーサイドレンダリング、ビルド時の統合、またはカスタム 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 を初期化する**

docs サイトの 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 タブを使用する場合は、 `allow="clipboard-write"` を iframe に設定してください。NPM パッケージでは iframe の設定はお任せします。スタンドアロンの [Script タグ](/docs/documentation/ja-gitbook-documentation/docs-site/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");

// Assistant タブに切り替える
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: 'ようこそ！', subtitle: 'どのようにお手伝いできますか？' },
  assistantName: 'Support Copilot',
  closeButton: true,
  suggestions: ['GitBook とは？', 'どうやって始めればよいですか？'],
  tools: [/* ... */]
});
```

{% endstep %}

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

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

```javascript
frame.on('close', () => {
  console.log('フレームが閉じられました');
});

// 完了したら解除する
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` - イベントリスナーを登録します（解除関数を返します）

## 設定オプション

ほとんどのカスタマイズオプションは次から利用できます: `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 に表示されるアシスタント名を上書きします。

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

#### `closeButton`

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

* **型**: `boolean`

#### `suggestions`

Assistant のウェルカム画面に表示される提案質問。

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

#### `trademark`

埋め込み UI で GitBook の商標を表示または非表示にします — Docs Embed のフッターと Assistant のブランディングを含みます。

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

#### `tools`

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

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

### Frame URL オプション

一部のオプションは次に渡されます: `getFrameURL({...})`.

#### `colorScheme`

埋め込みの配色を上書きします。

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

* **型**: `'light' | 'dark'`

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

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

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

## よくある落とし穴

* **パッケージのインストールを忘れる** – 実行します `npm install @gitbook/embed` をインポートする前に。
* **siteURL の指定漏れ** – `siteURL` オプションは必須で、公開済みの docs サイトと一致している必要があります。
* **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 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/docs-site/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.
