# @brainfish-ai/web-widget 中文文档

规范地址：https://npmcn.com/package/%40brainfish-ai/web-widget/

版本：1\.25\.7
npm 元数据更新时间：2026-11-05T03:18:51.054Z
中文译文更新时间：2026-11-08T13:41:28.361Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40brainfish-ai/web-widget
原文对照：https://npmcn.com/package/%40brainfish-ai/web-widget/?lang=original

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：244 kB，63 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：3 个
- 首次发布：2024-08-05T08:09:20.530Z
- 最新版本发布：2026-11-05T03:18:50.881Z
- 近 30 天下载量：24406（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：257（近 12 个月 32 个）

## 中文简介

Brainfish 部件管理器

## 安装

```sh
npm install @brainfish-ai/web-widget
```

也可以使用：`pnpm add @brainfish-ai/web-widget`、`yarn add @brainfish-ai/web-widget`、`bun add @brainfish-ai/web-widget`

## README

# 脑鱼入App部件

这个软件包提供了将Brainfish in-app部件整合到您网站或网络应用程序的简单方法. 它支持带有上下文帮助功能的弹出部件.

## 安装

```bash
npm install @brainfish-ai/web-widget
```

### 直接输入您的 HTML

```html
<script type="module">
    import Brainfish from "https://cdn.jsdelivr.net/npm/@brainfish-ai/web-widget@latest/dist/web.js"
    Brainfish.Widgets.init({ widgetKey: "your-key" });
</script>
```

## 弹出部件

弹出部件提供了一个浮动按钮,在模式覆盖中打开了搜索界面.

### 基本用途

```html
<!-- The widget will automatically create a floating button -->
<script>
    Brainfish.Widgets.init({
        widgetKey: "your-widget-key",
        environment: "production" // or "staging", "local"
    });
</script>
```

### 部件控制 API

```javascript
// Open the widget
Brainfish.Widgets.open();

// Open the widget with custom positioning
Brainfish.Widgets.open({
    position: 'bottom-right' // 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'
});

// Close the widget
Brainfish.Widgets.close();

// Create a new conversation thread
// If widget is open, resets the current conversation
// If widget is closed, opens it with a new conversation
Brainfish.Widgets.createNewThread();

// Check if widget is ready
if (Brainfish.Widgets.isReady) {
    // Widget is ready to use
}
```

### 用户管理

```javascript
// Identify a user
Brainfish.Widgets.identify({
    name: "John Doe",
    email: "john@example.com",
    userId: "user_123"
});

// Set secret attributes (for internal use)
Brainfish.Widgets.setSecretAttributes("internal_data_123");
```

### 带有覆盖的自定义

自定义部件的外观和行为 `overrides` 配置 :

```javascript
Brainfish.Widgets.init({
    widgetKey: "your-widget-key",
    overrides: {
        // Suggested questions that appear when widget opens
        suggestions: [
            'How do I reset my password?',
            'How do I contact support?',
            'What are your pricing plans?'
        ],

        // Theme customization
        theme: {
            inputButtonBgColor: '#3b82f6',
            inputButtonColor: '#ffffff'
        },

        // Widget settings
        panelTitle: 'Help Center',
        placeholder: 'Ask a question...',

        // Action buttons
        bodyActionButtons: [
            {
                icon: 'Calendar',
                type: 'link',
                label: 'Book a Demo',
                value: 'https://calendly.com/your-company'
            }
        ]
    }
});
```

**\* 完整的定制选项见:**

-   [**覆盖指南**](https://help.brainfi.sh/articles/brainfish-widget-overrides-guide-K96JtYxorD) - 完成附有实例的文件
-   [**快速引用**](https://help.brainfi.sh/articles/brainfish-widget-overrides-guide-K96JtYxorD#h-settings-reference) - 快速查找常见配置

### 自定义定位

两者 `open()` 财务报告和审定财务报表 `onContextHelp()` 方法支持自定义定位,以控制屏幕上显示部件的位置。 这对于创造背景经验或避免UI冲突是有用的.

**可用职位 :**

-   `'bottom-left'` - 部件出现在左下角(默认)
-   `'bottom-right'` - 部件出现在右下角
-   `'top-left'` - 部件出现在左上角
-   `'top-right'` - 部件出现在右上角

**使用实例:**

```javascript
// Open widget in different positions
Brainfish.Widgets.open({ position: 'top-right' });
Brainfish.Widgets.open({ position: 'bottom-left' });

// Contextual help with positioning
Brainfish.Widgets.onContextHelp("How do I reset my password?", {
    position: 'top-left'
});

// Dynamic positioning based on user interaction
function showHelpNearElement(question, element) {
    const rect = element.getBoundingClientRect();
    const position = rect.left < window.innerWidth / 2 ? 'bottom-left' : 'bottom-right';

    Brainfish.Widgets.onContextHelp(question, { position });
}
```

### 背景帮助特性

上下文帮助功能允许您打开基于用户交互的预填问题部件 .

```javascript
// Trigger contextual help with a specific question
Brainfish.Widgets.onContextHelp("How do I reset my password?");

// Trigger contextual help with custom positioning
Brainfish.Widgets.onContextHelp("How do I reset my password?", {
    position: 'top-left' // 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'
});
```

#### 执行实例

**带有帮助图标的 HTML :**

```html
<div class="form-field">
    <label>Email Address</label>
    <input type="email" value="user@example.com">
    <button class="help-icon"
            data-question="How do I change my email address?"
            data-position="top-left">
        <i class="ph ph-question"></i>
    </button>
</div>

<script>
// Add event listeners to help icons with custom positioning
document.querySelectorAll('.help-icon').forEach(icon => {
    icon.addEventListener('click', (e) => {
        const question = e.target.dataset.question;
        const position = e.target.dataset.position || 'bottom-right';
        Brainfish.Widgets.onContextHelp(question, { position });
    });
});
</script>
```

**直接按钮集成 :**

```html
<button onclick="Brainfish.Widgets.onContextHelp('How do I reset my password?', { position: 'top-right' })">
    Reset Password
</button>
```

**程序用途 :**

```javascript
function showHelp(question, position = 'bottom-right') {
    Brainfish.Widgets.onContextHelp(question, { position });
}

// Usage with different positions
showHelp("How do I update my profile?", 'top-left');
showHelp("How do I contact support?", 'bottom-right');
```

### 活动听众

部件打开和关闭时会发出事件 。 你可以听这些事件:

```javascript
// Set up the abort controller
const controller = new AbortController();
const { signal } = controller;

// Listen for widget events
window.addEventListener('onBrainfishWidgetOpen', (event) => {
    console.log('Widget opened');
    // Your custom logic here
}, { signal });

window.addEventListener('onBrainfishWidgetClose', (event) => {
    console.log('Widget closed');
    // Your custom logic here
}, { signal });

// Clean up event listeners when no longer needed
controller.abort();
```

### 分析事件

部件自动跟踪分析事件 :

-   **打开部件** - 当部件打开时
-   **打开部件 - 背景帮助** - 通过上下文帮助打开时
-   **打开部件 - 自定义触发器** - 用自定义触发器打开时
-   **关闭部件** - 当部件关闭时

## 构建

运行以下命令来构建部件 :

```bash
yarn build:web-widget
```

## 本地测试

### 启动本地服务器

```bash
cd packages/web-widget
npx serve ./ -p 8000 -C
```

### 打开游戏场

该游乐场为Brainfish部件提供了全面的测试环境:

```bash
open http://localhost:8000/playground/index.html
```

游乐场包括:

-   **部件配置** - 设置环境、 API 密钥和部件设置
-   **环境帮助测试** - 测试新的背景帮助功能,以抽样提问
-   **现实世界民主** - 看看客户如何在应用程序中实施背景帮助
-   **API 测试** - 测试所有部件方法和功能
-   **实时日志** - 监视部件事件并调试信息

### 测试不同的环境

您可以在不同的环境下测试部件, 方法是通过 `env` 参数 :

```bash
# Local environment
open http://localhost:8000/playground/index.html?env=local

# Staging environment
open http://localhost:8000/playground/index.html?env=staging

# Production environment
open http://localhost:8000/playground/index.html?env=prod
```

### 代理部件开发

如果您想用代理部件( Next.js app) 进行测试, 请在本地启动 :

```bash
cd packages/agent-widget
npm run dev
```

这将运行端口3000上的代理部件, 游乐场将在本地开发模式下自动连接到此部件 .

## 常见问题

### @brainfish-ai/web-widget 是什么？

Brainfish 部件管理器

### 如何安装 @brainfish-ai/web-widget？

在项目目录运行 npm install @brainfish-ai/web-widget，或使用 pnpm add / yarn add / bun add。

### @brainfish-ai/web-widget 支持 TypeScript 吗？

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

### @brainfish-ai/web-widget 支持 ESM 还是 CommonJS？

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

### @brainfish-ai/web-widget 可以商用吗？

@brainfish-ai/web-widget 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @brainfish-ai/web-widget 的下载量有多少？

根据 npm 官方下载统计，@brainfish-ai/web-widget 在 2026/10/09 – 2026/11/07 这 30 天内被下载 24,406 次，日均约 814 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @brainfish-ai/web-widget 还在维护吗？

最新版本 1\.25\.7 发布于 2026/11/05（3 天前）；至今共发布 257 个版本，其中过去 12 个月发布了 32 个；首次发布于 2024/08/05。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

