@elastic/behavioral-analytics-javascript-tracker

中文文档
2.1.4发布于 2023/05/22TypeScriptESM + CJS近 30 天下载 4091

Installation

原始使用文档
文档目录19 节
  1. Javascript Tracker
  2. Installation
  3. Usage
  4. Initialize tracker
  5. Token Fingerprints
  6. Changing the User Token and time length
  7. Introducing sampling
  8. Integration with Search UI (TODO)
  9. Dispatch Page View Events
  10. Dispatch Search Events
  11. Dispatch Search Click Events
  12. Common Issues
  13. When I try to dispatch an event, I get the following error:…
  14. API Methods
  15. createTracker
  16. trackPageView
  17. trackSearch
  18. trackSearchClick
  19. getTracker

Javascript Tracker

Installation

You can install the tracker using npm or yarn:

yarn add @elastic/behavioral-analytics-javascript-tracker
## OR
npm install @elastic/behavioral-analytics-javascript-tracker

Usage

Import the tracker in your application.

import {
  createTracker,
  trackPageView,
  trackSearch,
  trackSearchClick,
} from "@elastic/behavioral-analytics-javascript-tracker";

Initialize tracker

use createTracker method to initialize the tracker with your DSN. You can find your DSN in the behavioral Analytics UI under Collection > Integrate. You will then be able to use the tracker to send events to behavioral Analytics.

import {
  createTracker,
  trackPageView,
  trackEvent,
} from "@elastic/behavioral-analytics-javascript-tracker";

createTracker({
  endpoint: "https://my-endpoint-url",
  collectionName: "website",
  apiKey: "<api-key>",
});

Token Fingerprints

When createTracker is called, the tracker will store two fingerprints in the browser cookie:

  • User Token - a unique identifier for the user. Stored under EA_UID cookie. Default Time length is 24 hours from the first time the user visits the site.
  • Session Token - a unique identifier for the session. Stored under EA_SID cookie. Time length is 30 minutes from the last time the user visits the site.

These fingerprints are used to identify the user across sessions.

Changing the User Token and time length

You can change the User Token and time length by passing in the token and lifetime parameters to the createTracker method.

You can also change the lifetime of the session token by passing in the session.lifetime parameter to the createTracker method.

createTracker({
  user: {
    token: () => "my-user-token", // can be a string too
    lifetime: 24 * 60 * 60 * 1000, // 24 hours
  },
  session: {
    lifetime: 30 * 60 * 1000, // 30 minutes
  },
  }
});

Introducing sampling

You don't always want all sessions to be sent to your Elastic cluster. You can introduce session-based sampling by adding sampling parameter to the createTracker method.

If sampling is set to 1 (default), all sessions will send events. If sampling is set to 0, no sessions will send events.

createTracker({
  // ... tracker settings
  sampling: 0.3, // 30% of sessions will send events to the server
});

Integration with Search UI (TODO)

If you use Search UI, you can use the AnalyticsPlugin hook to automatically track search events. You can find more information about the AnalyticsPlugin here.

import AnalyticsPlugin from "@elastic/search-ui-analytics-plugin";
import { getTracker } from "@elastic/behavioral-analytics-javascript-tracker";

const searchUIConfig = {
  ...
  plugins: [AnalyticsPlugin({
    client: getTracker()
  })],
  ...
}

Dispatch Page View Events

You can then use the tracker to track page views.

// track a page view

const SearchPage = (props) => {
  useEffect(() => {
    trackPageView({
      // optional
      document: {
        id: "search-page",
        index: "pages",
      },
    });
  }, []);

  return (
    <div>
      <h1>Search Page</h1>
    </div>
  );
};

Dispatch Search Events

These events are used to track the user's search behavior. You can dispatch these events by calling the trackSearch method.

Below is an example of how you can dispatch a search event when a user searches for a query, for a hypothetical search API.

import { trackSearch } from "@elastic/behavioral-analytics-javascript-tracker";

const getSearchResults = async (query: string) => {
  const results = await api.getSearchResults(query);
  trackSearch({
    search: {
      query: query,
      results: {
        // optional
        items: [],
        total_results: results.totalResults,
      },
    },
  });
};

A full list of properties that can be passed to the trackSearch method below:

trackSearch({
  search: {
    query: "laptop",
    filters: [
      // optional
      { field: "brand", value: ["apple"] },
    ],
    page: {
      //optional
      current: 1,
      size: 10,
    },
    results: {
      // optional
      items: [
        {
          document: {
            id: "123",
            index: "products",
          },
          page: {
            url: "http://my-website.com/products/123",
          },
        },
      ],
      total_results: 100,
    },
    sort: {
      name: "relevance",
    },
    search_application: "website",
  },
});

Dispatch Search Click Events

These events are used to track the user's search click behavior. Think of these events to track what the user is clicking on after they have performed a search. You can dispatch these events by calling the trackSearchClick method.

Below is an example of how you can dispatch a search click event when a user clicks on a search result, for a hypothetical search API.

import { trackSearchClick } from "@elastic/behavioral-analytics-javascript-tracker";

trackSearchClick({
  // document that they clicked on
  document: { id: "123", index: "products" },
  // the query and results that they used to find this document
  search: {
    query: "laptop",
    filters: [
      { field: "brand", value: ["apple"] },
      { field: "price", value: ["1000-2000"] },
    ],
    page: {
      current: 1,
      size: 10,
    },
    results: {
      items: [
        {
          document: {
            id: "123",
            index: "products",
          },
          page: {
            url: "http://my-website.com/products/123",
          },
        },
      ],
      total_results: 100,
    },
    sort: {
      name: "relevance",
    },
    search_application: "website",
  },
});

Common Issues

When I try to dispatch an event, I get the following error: behavioral Analytics: Tracker not initialized.

This means that the tracker has not been initialized. You need to initialize the tracker before you can dispatch events. You can do this by calling the createTracker method.

API Methods

createTracker

Initializes the tracker with the given configuration. This method must be called before you can use the tracker.

import { createTracker } from "@elastic/behavioral-analytics-javascript-tracker";

createTracker({
  endpoint: "https://my-analytics-dsn.elastic.co",
  collectionName: "website",
  apiKey: "<api-key>",
});

Example

createTracker({});

Parameters

NameTypeDescription
optionsTrackerOptionsThe options for the tracker.

TrackerOptions

Options for the tracker.

NameTypeDescription
user.token() => string | stringA string or a function that returns the user token.
user.lifetimenumberThe expiration date of the user token.
endpointstringThe endpoint for events. You can find your endpoint in the behavioral Analytics UI under Collection > Integrate.
collectionNamestringYou can find your collection name in the behavioral Analytics UI under Collection > Integrate.
apiKeystringThe apiKey for endpoint. You can find in the behavioral Analytics UI under Collection > Integrate.

trackPageView

Tracks a page view event.

trackPageView();

Example

import { trackPageView } from "@elastic/behavioral-analytics-javascript-tracker";

trackPageView({
  document: {
    id: "123",
    index: "products",
  },
});

Parameters

NameTypeDescription
propertiesPageViewInputPropertiesThe properties of the event.

trackSearch

Tracks a custom event.

trackSearch(
  properties: SearchEventInputProperties
)

Example

import { trackSearch } from "@elastic/behavioral-analytics-javascript-tracker";

trackSearch({
  search: {
    query: "laptop",
    filters: [
      { field: "brand", value: ["apple"] },
      { field: "price", value: ["1000-2000"] },
    ],
    page: {
      current: 1,
      size: 10,
    },
    results: {
      items: [
        {
          document: {
            id: "123",
            index: "products",
          },
          page: {
            url: "http://my-website.com/products/123",
          },
        },
      ],
      total_results: 100,
    },
    sort: {
      name: "relevance",
    },
    search_application: "website",
  },
});

trackSearchClick

Tracks a click thats related to a search event. Example of usage is when a user clicks on a result that came from a search query.

Must have either a document or page property. Optimally both.

trackSearchClick(
  properties: SearchClickEventInputProperties
)

Example

import { trackSearchClick } from "@elastic/behavioral-analytics-javascript-tracker";

trackSearchClick({
  document: {
    id: "123",
    index: "products",
  },
  page: {
    url: "http://my-website.com/products/123",
    title: "My Product",
  },
  search: {
    query: "laptop",
    filters: [
      { field: "brand", value: ["apple"] },
      { field: "price", value: ["1000-2000"] },
    ],
    page: {
      current: 1,
      size: 10,
    },
    results: {
      items: [
        {
          document: {
            id: "123",
            index: "products",
          },
          page: {
            url: "http://my-website.com/products/123",
          },
        },
      ],
      total_results: 100,
    },
    sort: {
      name: "relevance",
    },
    search_application: "website",
  },
});

Parameters

NameTypeDescription
propertiesSearchClickEventInputPropertiesThe properties of the event.

getTracker

Returns the tracker instance. Useful when used to integrate with Search UI Analytics Plugin.

import { getTracker } from "@elastic/behavioral-analytics-javascript-tracker";

const tracker = getTracker();

版本与发布记录

@elastic/behavioral-analytics-javascript-tracker 共发布 9 个版本,首次发布于 2022/12/14;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.1.4latest2023/05/223 年前
2.1.32023/05/043 年前
2.1.22023/05/043 年前
2.1.12023/05/043 年前
2.1.02023/05/033 年前
2.0.12023/05/033 年前

其他发布通道:next → 2.0.0-next.0。

关于 @elastic/behavioral-analytics-javascript-tracker 的常见问题

@elastic/behavioral-analytics-javascript-tracker 是什么?

Installation

如何安装 @elastic/behavioral-analytics-javascript-tracker?

在项目目录运行 npm install @elastic/behavioral-analytics-javascript-tracker,或使用 pnpm add / yarn add / bun add。

@elastic/behavioral-analytics-javascript-tracker 支持 TypeScript 吗?

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

@elastic/behavioral-analytics-javascript-tracker 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@elastic/behavioral-analytics-javascript-tracker 可以商用吗?

@elastic/behavioral-analytics-javascript-tracker 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@elastic/behavioral-analytics-javascript-tracker 的下载量有多少?

根据 npm 官方下载统计,@elastic/behavioral-analytics-javascript-tracker 在 2026/10/13 – 2026/11/11 这 30 天内被下载 4,091 次,日均约 136 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@elastic/behavioral-analytics-javascript-tracker 还在维护吗?

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