@gitbook/embed

中文文档
0.7.0发布于 2026/11/12Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 22万

Embeddable components for GitBook

原始使用文档
文档目录23 节
  1. As a standalone script from your docs site
  2. Example: Configuring the widget
  3. As a package from NPM
  4. As React components
  5. Method Comparison
  6. Method Signatures
  7. Standalone Script
  8. NPM Package
  9. React Components
  10. tabs
  11. defaultTab
  12. defaultPage
  13. closeButton
  14. trademark
  15. actions
  16. greeting
  17. assistantName
  18. suggestions
  19. tools
  20. visitor (Authenticated Access)
  21. colorScheme
  22. button
  23. License

GitBook Docs Embed (@gitbook/embed)

Embed your GitBook docs in your product or website.

The Docs Embed can contain three tabs:

  • Assistant: The GitBook Assistant - an AI-powered chat interface to help users find answers
  • Search: A search-focused surface for quickly finding pages and asking scoped questions
  • Docs: A browser for navigating your documentation site

The embed is set up automatically based on your site's configuration. You can optionally customize and override the configuration with custom actions, tools, suggested questions, Authenticated Access, and more. See the Configuration section for all available options.

Usage

As a standalone script from your docs site

All GitBook docs sites include a script to easily add the Docs Embed as a widget on your website.

The script is served at https://docs.company.com/~gitbook/embed/script.js.

You can find the embed script from your docs site settings, or you can copy the following and replace docs.company.com with your docs site hostname.

<script src="https://docs.company.com/~gitbook/embed/script.js"></script>

The script initializes the widget itself, so there is nothing to call. To pin the embed to one color scheme, put it on the script URL — it has to be known before the widget renders:

<script src="https://docs.company.com/~gitbook/embed/script.js?theme=light"></script>

To authenticate the visitor, call init with their token. Keep tokens out of the script URL: it is publicly cacheable and ends up in server logs.

<script src="https://docs.company.com/~gitbook/embed/script.js"></script>
<script>
window.GitBook('init',
    { siteURL: 'https://docs.company.com' },
    { visitor: { token: 'your-jwt-token' } }
);
</script>

The standalone script provides a global GitBook function. See the API Reference section for all available methods.

Example: Configuring the widget

GitBook('configure', {
    button: {
        label: 'Ask',
        icon: 'assistant' // 'assistant' | 'sparkle' | 'help' | 'book'
    },
    tabs: ['assistant', 'search', 'docs'],
    defaultPage: '/getting-started',
    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 Assistant',
    suggestions: ['What is GitBook?', 'How do I get started?'],
    tools: [/* ... */],
    closeButton: true,
});

See the Configuration section for all available options.

As a package from NPM

Install the package: npm install @gitbook/embed and import it in your web application:

import { createGitBook } from '@gitbook/embed';

const gitbook = createGitBook({
    siteURL: 'https://docs.company.com'
});

// Create an iframe and get its URL
const iframe = document.createElement('iframe');
iframe.src = gitbook.getFrameURL({
    colorScheme: 'dark', // Optional: force the embed to render in dark mode
    visitor: {
        token: 'your-jwt-token', // Optional: for Adaptive Content or Authenticated Access
        unsignedClaims: { // Optional: custom claims for dynamic expressions
            userId: '123',
            plan: 'premium'
        }
    }
});

// Create a frame client to communicate with the iframe
const frame = gitbook.createFrame(iframe);

// Use the frame client methods
frame.navigateToPage('/getting-started'); // Navigate to a page in the docs tab
frame.navigateToAssistant(); // Switch to the assistant tab
frame.postUserMessage('How do I get started?');
frame.clearChat();

// Configure the embed (see Configuration section for all options)
frame.configure({
    tabs: ['assistant', 'search', 'docs'],
    defaultPage: '/getting-started',
    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 Assistant',
    suggestions: ['What is GitBook?', 'How do I get started?'],
    tools: [/* ... */],
    closeButton: true
});

// Listen to events
frame.on('close', () => {
    console.log('Frame closed');
});

As React components

After installing the NPM package, you can import prebuilt React components:

import { GitBookProvider, GitBookFrame } from '@gitbook/embed/react';

<GitBookProvider siteURL="https://docs.company.com">
    <GitBookFrame
        colorScheme="dark"
        visitor={{
            token: 'your-jwt-token', // Optional: for Adaptive Content or Authenticated Access
            unsignedClaims: { userId: '123' } // Optional: custom claims for dynamic expressions
        }}
        tabs={['assistant', 'search', 'docs']}
        defaultPage="/getting-started"
        greeting={{ title: 'Welcome!', subtitle: 'How can I help?' }}
        assistantName="Support Assistant"
        suggestions={['What is GitBook?', 'How do I get started?']}
        actions={[
            {
                icon: 'circle-question',
                label: 'Contact Support',
                onClick: () => window.open('https://support.example.com', '_blank')
            }
        ]}
        tools={[/* ... */]}
        closeButton
    />
</GitBookProvider>

You can also use the useGitBook hook to access the client:

import { useGitBook } from '@gitbook/embed/react';

function MyComponent() {
    const gitbook = useGitBook();
    const frameURL = gitbook.getFrameURL({ colorScheme: 'dark', visitor: { token: '...' } });
    // ...
}

API Reference

Method Comparison

MethodStandalone ScriptNPM PackageReact Components
InitializeGitBook('init', options, frameOptions)createGitBook(options)<GitBookProvider siteURL="...">
Get frame URL❌ (handled internally)client.getFrameURL(options)useGitBook().getFrameURL(options)
Create frame client❌ (handled internally)client.createFrame(iframe)useGitBook().createFrame(iframe)
Show/Hide widgetGitBook('show') / GitBook('hide')❌❌
Open/Close windowGitBook('open') / GitBook('close') / GitBook('toggle')❌❌
Navigate to pageGitBook('navigateToPage', path)frame.navigateToPage(path)Via frame client
Navigate to assistantGitBook('navigateToAssistant')frame.navigateToAssistant()Via frame client
Post messageGitBook('postUserMessage', message)frame.postUserMessage(message)Via frame client
Clear chatGitBook('clearChat')frame.clearChat()Via frame client
ConfigureGitBook('configure', settings)frame.configure(settings)Props on <GitBookFrame>
Event listeners❌frame.on(event, listener)Via frame client
UnloadGitBook('unload')❌❌

Method Signatures

Standalone Script

  • GitBook('init', options: { siteURL: string }, frameOptions?: { colorScheme?: 'light' | 'dark', visitor?: {...} }) - Initialize widget
  • GitBook('show') - Show widget button
  • GitBook('hide') - Hide widget button
  • GitBook('open') - Open widget window
  • GitBook('close') - Close widget window
  • GitBook('toggle') - Toggle widget window
  • GitBook('navigateToPage', path: string) - Navigate to page (accepts the page path within the site, an absolute path, or the full published URL; resolves pages in any space/section)
  • GitBook('navigateToAssistant') - Navigate to assistant tab
  • GitBook('postUserMessage', message: string) - Post message to chat
  • GitBook('clearChat') - Clear chat history
  • GitBook('configure', settings: {...}) - Configure widget
  • GitBook('unload') - Unload widget

NPM Package

Client Factory:

  • createGitBook(options: { siteURL: string }) → GitBookClient
  • client.getFrameURL(options?: { colorScheme?: 'light' | 'dark', visitor?: {...} }) → string
  • client.createFrame(iframe: HTMLIFrameElement) → GitBookFrameClient

Frame Client:

  • frame.navigateToPage(path: string) → void (accepts the page path within the site, an absolute path, or the full published URL; resolves pages in any space/section)
  • frame.navigateToAssistant() → void
  • frame.postUserMessage(message: string) → void
  • frame.clearChat() → void
  • frame.configure(settings: Partial<GitBookEmbeddableConfiguration>) → void
  • frame.on(event: string, listener: Function) → () => void (unsubscribe)

React Components

Components:

  • <GitBookProvider siteURL: string> - Provider component
  • <GitBookFrame {...props}> - Frame component (accepts all config options as props)

Hooks:

  • useGitBook() → GitBookClient (must be used within <GitBookProvider>)

Configuration

Configuration options are available across usage methods as follows:

  • Standalone script: via GitBook('configure', {...})
  • NPM package: via frame.configure({...})
  • React components: via props on <GitBookFrame>

tabs

Available in: Standalone script, NPM package, React components

Override which tabs are displayed. Defaults to your site's configuration.

  • Type: ('assistant' | 'search' | 'docs')[]
tabs: ['assistant', 'search', 'docs']

defaultTab

Available in: Standalone script, NPM package, React components

The tab the embed opens on. Without it, the embed opens on defaultPage if set, otherwise on the assistant (or the docs when the assistant isn't available). The tab must be one of the enabled tabs.

  • Type: 'assistant' | 'search' | 'docs'
tabs: ['assistant', 'search', 'docs'],
defaultTab: 'search'

defaultTab and defaultPage apply when the embed first loads: the standalone widget keeps its place when it is closed and reopened. To move it later, use navigateToPage or navigateToAssistant.

defaultPage

Available in: Standalone script, NPM package, React components

The page the docs tab opens on, in place of your site's home page. Accepts the same references as navigateToPage: the page's path within the site, an absolute path, or its full published URL. Unless defaultTab says otherwise, the embed opens on this page.

  • Type: string
defaultPage: '/getting-started/quickstart'

closeButton

Available in: Standalone script, NPM package, React components

Display a close (x) button in the embed sidebar.

  • Type: boolean
  • Default: false
closeButton: true

Behavior:

  • When clicked, the embed sends a close event to the parent page.
  • In the standalone script, this event is handled automatically and the widget closes.
  • In custom iframe integrations (NPM package), you must listen for the close event and decide how to hide/collapse your UI.
  • In React, this works automatically when using the standard widget flow. If you build custom frame wiring, handle close the same way as the NPM package.

NPM package example:

const frame = gitbook.createFrame(iframe);

frame.configure({
    closeButton: true
});

const unsubscribe = frame.on('close', () => {
    // Hide your modal/drawer/container
    container.classList.add('hidden');
});

Notes:

  • The close button is rendered in the same sidebar area as tabs/actions.
  • If your UI hides that sidebar or doesn't render it, the button will not be visible.

trademark

Available in: Standalone script, NPM package, React components

Display GitBook branding in the embed. Defaults to true.

  • Type: boolean
  • Default: true
trademark: true

actions

Available in: Standalone script, NPM package, React components

Custom action buttons rendered in the sidebar alongside tabs. Each action button triggers a callback when clicked.

Note: This prop was previously named buttons. Use actions instead, it has the same functionality.

  • Type: GitBookEmbeddableActionDefinition[]
  • Properties:
    • icon: string - Icon name. Any FontAwesome icon is supported. (e.g., 'rocket', 'comments', 'user-circle', ...)
    • label: string - Button label text
    • onClick: () => void | Promise<void> - Callback function when clicked
actions: [
    {
        icon: 'comments',
        label: 'Contact Support',
        onClick: () => window.open('https://support.example.com', '_blank')
    },
    {
        icon: 'rocket',
        label: 'Get started',
        onClick: () => {
            GitBook('navigateToPage', '/getting-started');
        }
    }
]

greeting

Available in: Standalone script, NPM package, React components

Welcome message displayed in the Assistant tab.

  • Type: { title: string, subtitle: string }
greeting: {
    title: 'Welcome!',
    subtitle: 'How can I help you today?'
}

assistantName

Available in: Standalone script, NPM package, React components

Override the assistant name displayed in the chat header and assistant entry points (for example, sidebar tabs and action labels). This name will be limited to 32 characters to prevent text overflow.

  • Type: string
assistantName: 'Support Assistant'

suggestions

Available in: Standalone script, NPM package, React components

Suggested questions displayed in the Assistant welcome screen.

  • Type: string[]
suggestions: [
    'What is GitBook?',
    'How do I get started?',
    'What can you do?'
]

tools

Available in: Standalone script, NPM package, React components

Custom AI tools to extend the Assistant. Tools allow the assistant to execute functions and integrate with your own systems.

Note: In addition to custom tools, the Assistant will always have access to any MCP servers you define in your site's AI settings.

  • Type: GitBookToolDefinition[]
  • Properties:
    • name: string - Unique tool identifier
    • description: string - Description of what the tool does (used by the AI to decide when and how to use it).
    • inputSchema: object - JSON schema defining the tool's input parameters
    • execute: (input: object) => Promise<{ output: any, summary: string }> - Async function that executes the tool.
      • output: The result of the tool execution, provided to the AI to continue working with. Not shown to the user.
      • summary: The visual summary of the tool execution, shown in the user's chat window.
    • confirmation: { icon?: string, label: string } (optional) - Confirmation button shown before execution, useful for actions that require the user's express approval.
tools: [
    {
        name: 'get_user_info',
        description: 'Get information about the current user',
        inputSchema: {
            type: 'object',
            properties: {
                userId: { 
                    type: 'string', 
                    description: 'The user ID to look up' 
                }
            },
            required: ['userId']
        },
        execute: async (input) => {
            const user = await fetch(`/api/users/${input.userId}`).then(r => r.json());
            return {
                output: { name: user.name, plan: user.plan },
                summary: `Retrieved info for user ${user.name}`
            };
        }
    },
    {
        name: 'create_ticket',
        description: 'Create a support ticket',
        confirmation: {
            icon: 'circle-question',
            label: 'Create support ticket?'
        },
        inputSchema: {
            type: 'object',
            properties: {
                subject: { type: 'string' },
                description: { type: 'string' }
            },
            required: ['subject', 'description']
        },
        execute: async (input) => {
            const ticket = await fetch('/api/tickets', {
                method: 'POST',
                body: JSON.stringify(input)
            }).then(r => r.json());
            return {
                output: { ticketId: ticket.id },
                summary: `Created ticket #${ticket.id}`
            };
        }
    }
]

visitor (Authenticated Access)

Available in: Standalone script (via init), NPM package (via getFrameURL()), React components (as prop)

Authenticated Access options passed when creating the frame URL. Used for Adaptive Content and Authenticated Access.

Note: This is not a configuration option but rather a parameter when initializing the frame or creating the frame URL.

Standalone script: Pass as the second argument to GitBook('init', options, frameOptions) NPM package: Pass to getFrameURL({ visitor: {...} }) React components: Pass as the visitor prop on <GitBookFrame>

  • Type: { token?: string, unsignedClaims?: Record<string, unknown> }
  • Properties:
    • token: string (optional) - Signed JWT token for Adaptive Content or Authenticated Access
    • unsignedClaims: Record<string, unknown> (optional) - Unsigned claims that can be used in dynamic expressions via visitor.claims.unsigned.<claim-name>
visitor: {
    token: 'your-jwt-token',
    unsignedClaims: {
        userId: '123',
        plan: 'premium',
        role: 'admin'
    }
}

colorScheme

Available in: Standalone script (via init), NPM package (via getFrameURL()), React components (as prop)

Override the embed's color scheme.

When omitted, the standalone widget follows the page it is embedded in — its color-scheme, falling back to the visitor's OS preference only when that page declares support for both. With the NPM package or the React components you own the iframe, so the embed follows the visitor's OS preference unless you pass this.

Note: This is not a configuration option but rather a parameter when initializing the frame or creating the frame URL.

Standalone script: ?theme=light on the script URL NPM package: Pass to getFrameURL({ colorScheme: 'dark' }) React components: Pass as the colorScheme prop on <GitBookFrame>

  • Type: 'light' | 'dark'
<script src="https://docs.company.com/~gitbook/embed/script.js?theme=light"></script>

Sites published with a single theme always render in that theme, so colorScheme has no effect on them — the widget follows the site instead, to keep its chrome and the docs inside it consistent.

button

Available in: Standalone script only

Configure the widget button for the standalone script. This option is not available when using the NPM package or React components, since they can be customized completely.

  • Type: { label: string, icon: 'assistant' | 'sparkle' | 'help' | 'book' }
  • Properties:
    • label: string - Button label text
    • icon: 'assistant' | 'sparkle' | 'help' | 'book' - Icon displayed on the button. Choose from one of 4 presets.
button: {
    label: 'Ask',
    icon: 'assistant'
}

License

Distributed under the Apache License 2.0.

版本与发布记录

@gitbook/embed 共发布 13 个版本,首次发布于 2025/08/26;过去 12 个月发布了 8 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.7.0latest2026/11/124 天前
0.6.02026/10/2819 天前
0.5.12026/05/195 个月前
0.4.02026/03/118 个月前
0.3.02026/03/058 个月前
0.2.22026/02/258 个月前

关于 @gitbook/embed 的常见问题

@gitbook/embed 是什么?

Embeddable components for GitBook

如何安装 @gitbook/embed?

在项目目录运行 npm install @gitbook/embed,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(*)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gitbook/embed 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gitbook/embed 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@gitbook/embed 可以商用吗?

@gitbook/embed 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@gitbook/embed 的下载量有多少?

根据 npm 官方下载统计,@gitbook/embed 在 2026/10/17 – 2026/11/15 这 30 天内被下载 219,643 次,日均约 7,321 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gitbook/embed 还在维护吗?

最新版本 0.7.0 发布于 2026/11/12(4 天前);至今共发布 13 个版本,其中过去 12 个月发布了 8 个;首次发布于 2025/08/26。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。