npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@amplitude/marketing-analytics-browser

v1.0.16

Published

Official Amplitude SDK for Web and Marketing Analytics

Downloads

38,272

Readme

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:

  • NPM: https://www.npmjs.com/package/@amplitude/analytics-browser
  • GitHub: https://github.com/amplitude/Amplitude-TypeScript
  • Documentation: https://www.docs.developers.amplitude.com/data/sdks/browser-2/

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}},s=function(e,t,r){return function(n){e._q.push({name:t,args:Array.prototype.slice.call(r,0),resolve:n})}},o=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(s(e,t,Array.prototype.slice.call(arguments)))};o(e,t,Array.prototype.slice.call(arguments))}},a=function(e){for(var t=0;t<g.length;t++)i(e,g[t],!1);for(var r=0;r<m.length;r++)i(e,m[r],!0)};r.invoked=!0;var c=t.createElement("script");c.type="text/javascript",c.integrity="sha384-ikQAMTzbYOBfnIGKD7dLuUure2HHyvjVswubQx326AW+CdL4JnnvPMXFJaTo5c16",c.crossOrigin="anonymous",c.async=!0,c.src="https://cdn.amplitude.com/libs/marketing-analytics-browser-1.0.16-min.js.gz",c.onload=function(){e.amplitude.runQueuedFunctions||console.log("[Amplitude] Error: could not load SDK")};var u=t.getElementsByTagName("script")[0];u.parentNode.insertBefore(c,u);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"],y=0;y<v.length;y++)n(f,v[y]);r.Revenue=f;var g=["getDeviceId","setDeviceId","getSessionId","setSessionId","getUserId","setUserId","setOptOut","setTransport","reset"],m=["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();