@beacon.li/bar

中文文档
0.0.23发布于 2026/11/05MITTypeScriptES Module零依赖近 30 天下载 5018

shell npm install @beacon.li/bar

原始使用文档
文档目录19 节
  1. Installation
  2. Usage
  3. Loading User Data
  4. Authenticated users (authDetails)
  5. Native Routing
  6. Open and Close programmatically
  7. Callbacks
  8. Trigger smart journeys
  9. Execute command
  10. Open Help Docs
  11. Emitting Events
  12. Listening to events from Beacon Bar
  13. Adding event listener
  14. Removing event listener
  15. Example react fragment to manipulate state with react and e…
  16. List of events emitted by Beacon Bar
  17. Chat and agents
  18. UI customisation
  19. CSP

Beacon Bar

Installation

npm install @beacon.li/bar

OR

yarn add @beacon.li/bar

Usage

import {Beacon} from '@beacon.li/bar';

Beacon.load('ORG_ID');

Next.js

import {Beacon} from '@beacon.li/bar';

if (typeof window !== 'undefined') {
    Beacon.load('ORG_ID');
}

Loading User Data

Params

  • userId (string) :- The unique identifier of the user — can be email or database id
  • metaData (object) :- The object containing the user data to be passed to the Beacon Bar
  • authDetails (object | function | string) (optional) :- Auth tokens for the user, see Authenticated users
import {Beacon} from '@beacon.li/bar';

Beacon.loadUser(userId, {
    name: 'John Doe',
    isPremiumUser: true,
    currentPlan: 'Premium'
})

Authenticated users (authDetails)

If auth is enabled for your org, pass the user's tokens as the third argument of loadUser. It accepts a token callback (recommended), a static token object, or a bare access token string.

Token callback

The callback is invoked on load, and again whenever the access token is about to expire (if no refresh token was returned) or the refresh fails. A failed call is retried up to 3 times before auth is cleared.

import {Beacon} from '@beacon.li/bar';

Beacon.loadUser(userId, {name: 'John Doe'}, async () => {
    const res = await fetch('/api/beacon-token');
    return res.json();
    // {accessToken, accessTokenExpiresAt?, refreshToken?, refreshTokenExpiresAt?}
});

Static tokens

Beacon.loadUser(userId, {}, {accessToken, accessTokenExpiresAt, refreshToken, refreshTokenExpiresAt});

Logout

Revokes the tokens on the server, clears local auth state and unloads the bar.

await Beacon.logout();

Native Routing

Vanilla JS
import {Beacon} from '@beacon.li/bar';

Beacon.setRouter(url => {
    // your logic here
});
React

in your main child component of your router:

import {Beacon} from '@beacon.li/bar';
import {useHistory} from 'react-router-dom';
import {useEffect} from 'react';

const history = useHistory();

useEffect(() => {
    Beacon.setRouter(path => {
        history.push(path);
    });
}, [history]);

Vue

in your main component:

import {Beacon} from '@beacon.li/bar';
import {useRouter} from 'vue-router';
import {onMounted} from 'vue';

export default {
    setup() {
        const router = useRouter();
        onMounted(() => {
            Beacon.setRouter(path => {
                router.push(path);
            });
        })
    }
}

Angular

In your main component:

import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {Beacon} from '@beacon.li/bar';

@Component({
    selector: 'app-my-component',
    templateUrl: './my-component.component.html',
    styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {

    constructor(private router: Router) {
    }

    ngOnInit() {
        Beacon.setRouter((path: string) => {
            this.router.navigateByUrl(path);
        });
    }
}

Open and Close programmatically

import {Beacon} from '@beacon.li/bar';

Beacon.open();

Beacon.close();

Callbacks

Add Callbacks

Adding callback multiple times will replace the old one

Params

  • key (string) :- The key of the callback
  • callback (function) :- The callback function to be executed
    • Signature :- (userId, metaData) => {}
    • userId (string) (default: beacon-anonymous) :- The unique identifier passed during loadUser
    • metaData (object) (default: {}) :- The metaData object passed during loadUser
import {Beacon} from '@beacon.li/bar';

Beacon.addCallback('your_callback_key', (userId, metaData) => {
    // your logic here
});

Remove Callbacks

Params

  • key (string) :- The key of the callback
import {Beacon} from '@beacon.li/bar';

Beacon.removeCallback('your_callback_key');

React Example

Example react fragment to manipulate state with react and callbacks

import {Beacon} from '@beacon.li/bar';
import {useEffect, useState} from 'react';

function Component() {
    const [state, setState] = useState(false);

    useEffect(() => {
        const callback = (userId, metaData) => {
            setState(true);
        }
        Beacon.addCallback('your_callback_key', callback);

        return () => {
            Beacon.removeCallback('your_callback_key');
        }
    }, [setState])
}

Trigger smart journeys

Trigger smart journeys from your app

Params

  • journeyId (string) :- The id of the journey
  • type (string) (optional) (default: main) :- The type of the journey (main, pinned, closed)
import {Beacon} from '@beacon.li/bar';

Beacon.startJourney('journeyId', 'main');

Execute command

Execute command from your app

Params

  • commandId (string) :- The id of the command
import {Beacon} from '@beacon.li/bar';

Beacon.executeCommand('commandId');

Open Help Docs

Open help docs from your app

Params

  • helpDocId (string) :- The id of the help doc
  • type (string) (optional) (default: default) :- The type of the help doc (default, max)
import {Beacon} from '@beacon.li/bar';

Beacon.openHelpDoc('helpDocId', 'default');

Emitting Events

Emit custom events to Beacon Bar and use them in rules and journeys

Params

  • eventName (string) :- The name of the event (only alphanumeric (a-zA-Z0-9), underscore (_) and hyphen (-) allowed)
  • attributes (object) (optional) :- The attributes to be passed with the event
import {Beacon} from '@beacon.li/bar';

Beacon.trackEvent('event_name', {
    // your attributes here
});

Listening to events from Beacon Bar

Listen to different analytical events emitted by Beacon Bar

Adding event listener

Params

  • function
    • Signature :- (eventName, attributes, userId) => {}
      • eventName (string) :- The name of the event
      • attributes (object) :- The attributes passed with the event
      • userId (string) (default: beacon-anonymous) :- The unique identifier passed during loadUser
import {Beacon} from '@beacon.li/bar';

Beacon.addEventListener((eventName, attributes, userId) => {

})

Removing event listener

import {Beacon} from '@beacon.li/bar';

Beacon.removeEventListener(func);

Example react fragment to manipulate state with react and event listener

import {Beacon} from '@beacon.li/bar';
import {useEffect} from 'react';

function Component() {
    useEffect(() => {
        const listener = (eventName, attributes, userId) => {
            // your logic here
        }

        Beacon.addEventListener(listener);

        return () => {
            Beacon.removeEventListener(listener);
        }
    }, [])
}

List of events emitted by Beacon Bar

Event NameAttributesDescription
barInvokedWhen the Beacon Bar is invoked
actionClicked_id, label, query, hasSearchWhen an action is clicked on the Beacon Bar
helpClicked_id, label, query, hasSearchWhen an help doc is clicked on the Beacon Bar
requestCommandClickedhasSearch, labelWhen a request new command is clicked on the Beacon Bar
feedbackClickedhasSearch, labelFeedback command clicked on Beacon Bar

Chat and agents

import {Beacon} from '@beacon.li/bar';

Beacon.openChat({message: 'Hi', source: 'chat', autoSend: true, active: true}); // source: chat | home | bar
Beacon.openNewChat({message: 'Hi', source: 'chat', autoSend: true});
Beacon.openThread({sessionId: 'SESSION_ID', query: ''});
Beacon.minimizeChat();
Beacon.closeChat();
Beacon.startNewChat();
await Beacon.endChatSession('SESSION_ID');   // ends the session, does not close the chat
const thread = Beacon.getCurrentChatThread();

const answer = await Beacon.runAgent({
    agentRouterId: 'AGENT_ID',
    query: 'Summarise my last order',
    sessionId: 'SESSION_ID',                  // optional
    callBack: text => {},                     // streamed text
});

Beacon.hideChatInvoker();
Beacon.showChatInvoker();

UI customisation

Beacon.setThemeColor('#1a73e8', '#e8f0fe');   // primary, secondary
Beacon.overrideUiConfig({/* partial org uiConfig */});

CSP

To ensure proper functionality of Beacon, our third-party JavaScript, on your web app while safeguarding your users against XSS vulnerabilities, it is necessary to include the minimal set of Content Security Policy (CSP) rules listed below.

script-src: https://*.beacon.li;
frame-src: https://*.beacon.li;
img-src: https://*.beacon.li;
media-src: https://*.beacon.li;
connect-src: https://*.beacon.li;
style-src: https://*.beacon.li;

版本与发布记录

@beacon.li/bar 共发布 24 个版本,首次发布于 2023/05/22;过去 12 个月发布了 2 个版本。

版本发布日期距今
0.0.23latest2026/11/052 天前
0.0.222026/06/055 个月前
0.0.212025/04/211.5 年前
0.0.202024/03/012 年前
0.0.192024/02/142 年前
0.0.182024/02/142 年前

关于 @beacon.li/bar 的常见问题

@beacon.li/bar 是什么?

shell npm install @beacon.li/bar

如何安装 @beacon.li/bar?

在项目目录运行 npm install @beacon.li/bar,或使用 pnpm add / yarn add / bun add。

@beacon.li/bar 支持 TypeScript 吗?

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

@beacon.li/bar 支持 ESM 还是 CommonJS?

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

@beacon.li/bar 可以商用吗?

@beacon.li/bar 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@beacon.li/bar 的下载量有多少?

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

@beacon.li/bar 还在维护吗?

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