Search documentation...

K
ChangelogBook a demoSign up

Browser (Javascript) SDK

The Browser SDK makes it easy to track events in webpages.

Installation

The Browser SDK can be installed by loading the Javascript via a script tag, or directly bundled via a npm package.

To install using a script tag, add the following snippet to your site, replacing WRITE_KEY with the write key from your Event Source:

<script type="text/javascript">
!function(){var e=window.htevents=window.htevents||[];if(!e.initialize)if(e.invoked)window.console&&console.error&&console.error("Hightouch snippet included twice.");else{e.invoked=!0,e.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware"],e.factory=function(t){return function(){var n=Array.prototype.slice.call(arguments);return n.unshift(t),e.push(n),e}};for(var t=0;t<e.methods.length;t++){var n=e.methods[t];e[n]=e.factory(n)}e.load=function(t,n){var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src="https://cdn.hightouch-events.com/browser/release/v1-latest/events.min.js";var r=document.getElementsByTagName("script")[0];r.parentNode.insertBefore(o,r),e._loadOptions=n,e._writeKey=t},e.SNIPPET_VERSION="0.0.1",
e.load('WRITE_KEY',{apiHost:'us-east-1.hightouch-events.com'}),
e.page()}}();
</script>

To install using npm:

  1. Install the SDK by running npm install @ht-sdks/events-sdk-js-browser
  2. Import and initialize the SDK with the following:
import { HtEventsBrowser } from "@ht-sdks/events-sdk-js-browser";
export const htevents = HtEventsBrowser.load(
  { writeKey: "WRITE_KEY" },
  { apiHost: "us-east-1.hightouch-events.com" }
);

API

Identify

The identify method is used to send an identify event.

If identify is called multiple times for the same user, the traits are merged together.

Method signature:

htevents.identify(userId, [traits], [context], [callback])

Method parameters:

ParameterTypeDescription
userIdStringThe user's persistent ID.
traitsObjectAdditional traits about the user, such as email and name.
contextObjectOverrides to values in the event context. By default, context contains information autocollected by the SDK.
callbackFunctionA callback that's invoked after the event is sent.

Track

The track method is used to send a track event.

Method signature:

htevents.track(event, [properties], [context], [callback])

Method parameters:

ParameterTypeDescription
eventStringThe event name (for example "Checked Out").
propertiesObjectAdditional properties about the event, such as product_id.
contextObjectOverrides to values in the event context. By default, context contains information autocollected by the SDK.
callbackFunctionA callback that's invoked after the event is sent.

Page

The page method is used to send a page event.

Method signature:

htevents.page(category, name, [properties], [context], [callback])

Method parameters:

ParameterTypeDescription
categoryStringThe page's category. For example, "Docs".
nameStringThe page's name. For example, "Getting started".
propertiesObjectAdditional properties about the event, such as url. By default, the SDK autocollects properties such as page referrer.
contextObjectOverrides to values in the event context. By default, context contains information autocollected by the SDK.
callbackFunctionA callback that's invoked after the event is sent.

Group

The group method sends a group event.

Method signature:

htevents.group(groupId, [traits], [context], [callback])

Method parameters:

ParameterTypeDescription
groupIdStringThe id for the group.
traitsObjectAdditional traits about the group, such as company_name.
contextObjectOverrides to values in the event context. By default, context contains information autocollected by the SDK.
callbackFunctionA callback that's invoked after the event is sent.

Reset

The reset method resets the identify and group for the local session. Specifically, it resets the anonymousId, userId, groupId, and traits.

The reset method should be called when users log out. This way, if the user logs back in with another account, the userIds and traits from the different sessions remain separate.

Method signature:

htevents.reset()

Single page applications

While Single Page Apps (SPAs) are great for many reasons, they do require some extra consideration in order to set up client-side tracking than with a traditional webpage.

By default, the Hightouch htevents.js library doesn't generate or store the referrer value. Instead, the referrer value you see in the payload is the value returned by document.referrer directly from the browser, and the URL value is the canonical URL on the page.

When a user navigates between pages on an SPA website, there won't be a referrer because there is no concept of a new page since it's all a single page load. This means that the referrer will always be the same as it was on the first page call where someone was first directed to your site. However, in order to circumvent this, you can manually set the referrer and URL in your Hightouch calls by updating the context object.

For example, a Page call with the referrer and URL manually set looks like this:

htevents.page({
  referrer: 'https://hightouch.com/',
  url: 'https://hightouch.com/pricing/?ref=nav'
})

A Track call with these fields manually updated looks like this:

htevents.track('Example Event', {}, {page: {
  referrer: 'https://hightouch.com/',
  url: 'https://hightouch.com/pricing/?ref=nav'
}})

Tracking emulated page views

Your application should update the URL in the address bar to emulate traditional webpage navigation. Full page requests aren't made in most of these instances since the resources are loaded on initial page load. This means that the Page call in the traditional htevents.js snippet won't fire again as a user navigates around your site.

You should still place the snippet in the head of your site, but you should remove the Page call and fire it whenever you're emulating a page load. Hightouch recommends that you call Page from the same block of logic that updates the view and URL path like below:

// The new view has been called to render
htevents.page("Home")

To track more than the page field, pass those fields in as additional properties. Hightouch recommends that you use variables to set information about page properties, rather than hard-coding. In most SPA frameworks, you can automate this by attaching the Page call to the routing service.

Tracking UTMs on a single-page application

Hightouch automatically captures UTMs that you pass in URLs. You can also manually pass UTMs into the context campaign fields.

Ready to get started?

Jump right in or a book a demo. Your first destination is always free.

Book a demoSign upBook a demo

Need help?

Our team is relentlessly focused on your success. Don't hesitate to reach out!

Feature requests?

We'd love to hear your suggestions for integrations and other features.

Last updated: Dec 6, 2023

On this page

InstallationAPIIdentifyTrackPageGroupResetSingle page applicationsTracking emulated page viewsTracking UTMs on a single-page application

Was this page helpful?