@amplitude/marketing-analytics-browser

中文文档
1.0.21发布于 2025/07/09MITTypeScriptESM + CJS近 30 天下载 7458

Official Amplitude SDK for Web and Marketing Analytics

原始使用文档
文档目录13 节
  1. Installation
  2. Using Node package
  3. Using script loader
  4. Usage
  5. Initializing SDK
  6. Tracking an Event
  7. User Properties
  8. prepend/append
  9. User Groups
  10. Group Identify
  11. Track Revenue
  12. Callback
  13. User Log out


Announcement 📣

The Marketing Analytics Browser SDK is currently in maintenance mode. Amplitude has introduced the Browser SDK 2.0 as its replacement. This SDK offers improved marketing attribution tracking, a simplified interface, and a more lightweight package.

To learn more about the Browser 2.0 SDK, here are some useful links:

Please check what has been improved and the detailed migration guide at the here.

@amplitude/marketing-analytics-browser

Official Amplitude SDK for Web and Marketing Analytics

Doc

See our Typescript Analytics Browser SDK Reference for a list and description of all available SDK methods.

Installation and Quick Start

Please visit our :100:Developer Center for instructions on installing and using our the SDK.

Installation

To get started with using Amplitude Marketing Analytics Browser SDK, install the package to your project via NPM or script loader.

Using Node package

This package is published on NPM registry and is available to be installed using npm and yarn.

# npm
npm install @amplitude/marketing-analytics-browser@^1.0.0

# yarn
yarn add @amplitude/marketing-analytics-browser@^1.0.0

Using script loader

Alternatively, the package is also distributed through a CDN. Copy and paste the script below to your html file.

<script type="text/javascript">
!function(){"use strict";!function(e,t){var r=e.amplitude||{_q:[],_iq:{}};if(r.invoked)e.console&&console.error&&console.error("Amplitude snippet has been loaded.");else{var n=function(e,t){e.prototype[t]=function(){return this._q.push({name:t,args:Array.prototype.slice.call(arguments,0)}),this}},o=function(e,t,r){return function(n){e._q.push({name:t,args:Array.prototype.slice.call(r,0),resolve:n})}},s=function(e,t,r){e._q.push({name:t,args:Array.prototype.slice.call(r,0)})},i=function(e,t,r){e[t]=function(){if(r)return{promise:new Promise(o(e,t,Array.prototype.slice.call(arguments)))};s(e,t,Array.prototype.slice.call(arguments))}},a=function(e){for(var t=0;t<y.length;t++)i(e,y[t],!1);for(var r=0;r<g.length;r++)i(e,g[r],!0)};r.invoked=!0;var u=t.createElement("script");u.type="text/javascript",u.integrity="sha384-GHMjupGoiEYbVNhlFaV8TE8oh4dmGkFVo8tK74+jPpn7juCuO7mO6vzBaDJNAxuz",u.crossOrigin="anonymous",u.async=!0,u.src="https://cdn.amplitude.com/libs/marketing-analytics-browser-1.0.21-min.js.gz",u.onload=function(){e.amplitude.runQueuedFunctions||console.log("[Amplitude] Error: could not load SDK")};var c=t.getElementsByTagName("script")[0];c.parentNode.insertBefore(u,c);for(var l=function(){return this._q=[],this},p=["add","append","clearAll","prepend","set","setOnce","unset","preInsert","postInsert","remove","getUserProperties"],d=0;d<p.length;d++)n(l,p[d]);r.Identify=l;for(var f=function(){return this._q=[],this},v=["getEventProperties","setProductId","setQuantity","setPrice","setRevenue","setRevenueType","setEventProperties"],m=0;m<v.length;m++)n(f,v[m]);r.Revenue=f;var y=["getDeviceId","setDeviceId","getSessionId","setSessionId","getUserId","setUserId","setOptOut","setTransport","reset"],g=["init","add","remove","track","logEvent","identify","groupIdentify","setGroup","revenue","flush"];a(r),r.createInstance=function(e){return r._iq[e]={_q:[]},a(r._iq[e]),r._iq[e]},e.amplitude=r}}(window,document)}();

amplitude.init("YOUR_API_KEY_HERE");
</script>

Usage

Initializing SDK

Initialization is necessary before any instrumentation is done. The API key for your Amplitude project is required.

amplitude.init(API_KEY);

// Config web attribution and auto page view tracking
amplitude.init(API_KEY, USER_ID, {
  // Config web attribution
  attribution: {
    resetSessionOnNewCampaign: true;
  },

  // Enable auto page view tracking
  pageViewTracking: {
    trackOn: 'attribution',
  }
});

Tracking an Event

Events represent how users interact with your application. For example, "Button Clicked" may be an action you want to note.

import { track } from '@amplitude/marketing-analytics-browser';

// Track a basic event
track('Button Clicked');

// Track events with additional properties
const eventProperties = {
  selectedColors: ['red', 'blue'],
};
track('Button Clicked', eventProperties);

User Properties

User properties help you understand your users at the time they performed some action within your app such as their device details, their preferences, or language.

import { Identify, identify } from '@amplitude/marketing-analytics-browser';

const event = new Identify();

// sets the value of a user property
event.set('key1', 'value1');

// sets the value of a user property only once
event.setOnce('key1', 'value1');

// increments a user property by some numerical value.
event.add('value1', 10);

// pre inserts a value or values to a user property
event.preInsert('ab-tests', 'new-user-test');

// post inserts a value or values to a user property
event.postInsert('ab-tests', 'new-user-test');

// removes a value or values to a user property
event.remove('ab-tests', 'new-user-test')

// sends identify event
identify(event);

prepend/append

  • append will append a value or values to a user property array.
  • prepend will prepend a value or values to a user property.

User Groups

import { setGroup } from '@amplitude/marketing-analytics-browser';

// set group with single group name
setGroup('orgId', '15');

// set group with multiple group names
setGroup('sport', ['soccer', 'tennis']);

Group Identify

This feature is only available to Growth and Enterprise customers who have purchased the Accounts add-on.

Use the Group Identify API to set or update properties of particular groups. However, these updates will only affect events going forward.

import { Identify, groupIdentify } from '@amplitude/marketing-analytics-browser';

const groupType = 'plan';
const groupName = 'enterprise';
const event = new Identify()
event.set('key1', 'value1');

groupIdentify(groupType, groupName, identify);

Track Revenue

Revenue instances will store each revenue transaction and allow you to define several special revenue properties (such as 'revenueType', 'productIdentifier', etc.) that are used in Amplitude's Event Segmentation and Revenue LTV charts. These Revenue instance objects are then passed into revenue to send as revenue events to Amplitude. This allows us to automatically display data relevant to revenue in the platform. You can use this to track both in-app and non-in-app purchases.

import { Revenue, revenue } from '@amplitude/marketing-analytics-browser';

const event = new Revenue()
  .setProductId('com.company.productId')
  .setPrice(3.99)
  .setQuantity(3);

revenue(event);

Callback

All asynchronous API are optionally awaitable through a specific Promise interface. This also serves as callback interface.

// Using async/await
const results = await track('Button Clicked').promise;
result.event; // {...} (The final event object sent to Amplitude)
result.code; // 200 (The HTTP response status code of the request.
result.message; // "Event tracked successfully" (The response message)

// Using promises
track('Button Clicked').promise.then((result) => {
  result.event; // {...} (The final event object sent to Amplitude)
  result.code; // 200 (The HTTP response status code of the request.
  result.message; // "Event tracked successfully" (The response message)
});

User Log out

This updates user ID and device ID. After calling reset() the succeeding events now belong to a new user identity.

import { reset } from '@amplitude/marketing-analytics-browser';

reset();

版本与发布记录

@amplitude/marketing-analytics-browser 共发布 70 个版本,首次发布于 2022/09/27;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.21latest2025/07/091.3 年前
1.0.202025/03/041.7 年前
1.0.192025/03/011.7 年前
1.0.182025/02/141.7 年前
1.0.172025/01/151.8 年前
1.0.162024/05/292 年前

关于 @amplitude/marketing-analytics-browser 的常见问题

@amplitude/marketing-analytics-browser 是什么?

Official Amplitude SDK for Web and Marketing Analytics

如何安装 @amplitude/marketing-analytics-browser?

在项目目录运行 npm install @amplitude/marketing-analytics-browser,或使用 pnpm add / yarn add / bun add。

@amplitude/marketing-analytics-browser 支持 TypeScript 吗?

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

@amplitude/marketing-analytics-browser 支持 ESM 还是 CommonJS?

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

@amplitude/marketing-analytics-browser 可以商用吗?

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

@amplitude/marketing-analytics-browser 的下载量有多少?

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

@amplitude/marketing-analytics-browser 还在维护吗?

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