Overview
Intempt's Javascript SDK enables data to be sent and tracked on the client's browser by using autotrack functionality or calling custom methods to track events.
Features
Autotrack events
Track custom events
Display client-side experiments (if an experiment is created)
Display client-side personalization campaigns (if a personalization is created)
Methods
Browser support
JavaScript SDK supports these browsers on which it was tested:
Chrome 121+
Edge 121+
Safari 17.3+
Firefox 122+
🚧 Don't miss out!
To display client-side experiments and personalization, ensure that if the website has CSP (Content-Security-Policy) rules, cdn.intempt.com is allowed by the website domain. That might affect any loadable resource from cdn.intempt.com, like images or CSS styles.
Installation
Create a Web tracker source
Under the Integrations section -> "Sources" tab, select the "Create source" button and then the "Web tracker" option.
Under “Installation,” copy the code block snippet containing the script tags and JavaScript function.
Initialize the SDK
Paste the snippet in the <head> tag section of your website. This should be an HTML page that acts as a base or template page (with other scripts your page loads) to ensure all possible events are captured.
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My awesome web-site</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script
async
src="https://cdn.intempt.com/v1/intempt.min.js?organization=your_organization&project=your_project&source=your_source_id&key=YOUR_API_KEY">
</script>
</head>
<body>
</body>
</html>
Supported event types
After the SDK is initialized, you can access two types of events tracked by the SDK.
Auto-tracked events
Some web tracker events are recorded automatically; you can use them as soon as the source is created.
Event | Description |
This event is triggered every time a user opens a new page on your website. | |
This event is recorded when a user leaves a page. | |
Capture this event every time a user clicks on a specific element, like buttons or links. It's crucial for understanding user behavior around key interactions on your site. | |
This event occurs whenever a user makes a change to a field in a form, such as selecting an option from a dropdown or toggling a switch. It helps track user preferences and input patterns. | |
Triggered when a user submits a form, this event is vital for tracking conversions and understanding how effectively your forms lead to user actions. | |
This event marks the beginning of a user's session on your site. | |
Recorded when a user's session ends, either by closing the browser, expiring the session timeout, or manually logging out. |
Custom events
Custom events are specific actions you define in your code that you want to track. Compared to autotrack events, which only require a tracking snippet to be added, custom events require advanced planning (refer to Complete guide to event tracking) and developer involvement to add the code to your website or application. After the custom event is tracked, it will automatically appear in the Events list.
Use the SDK methods below to perform custom event tracking.
SDK methods
Track
The track method is the simplest way to track events. It records event attributes present when the event was performed, including timestamps, IDs, amounts, and other event-specific information. Note that the track method does not allow tracking user attributes. Instead, use the identify or record methods.
Example
JavaScript
const trackParams = {
eventTitle: 'Purchase Completed',
data: {
itemId: 'SKU12345',
price: 29.99,
quantity: 1
}
};
intempt.track(trackParams);
In this example, the track method logs a product view event with additional data about the product, such as its ID, name, and price.
Declaration
The track method is declared as follows in TypeScript, highlighting that it does not return any value:
TypeScript
track(params: TrackParams): void
Parameters
The parameters for the track method are encapsulated within the TrackParams type, allowing for extensive customization and detailed event tracking:
TypeScript
type TrackParams = {
eventTitle: string, // Title of the event being tracked.
data: {[key:string]: any} // Additional data related to the event in a key-value pair format.
}
Record
The record method allows you to track everything about the event - including user or account attributes and identifying the user. We recommend using the record if you want to use a single method to track the event data.
Example
JavaScript
const recordParams = {
eventTitle: 'login',
userId: '[email protected]',
userAttributes: {
loginMethod: 'OAuth',
attemptCount: 3
},
data: {
ipAddress: '192.168.1.1'
}
};
intempt.record(recordParams);
In the example above, the record method tracks login event and identifies the user with [email protected], track user's attributes (loginMethod, attemptCount) and event attributes (ipAddress).
Declaration
The record method is declared as follows in TypeScript, signifying that it does not return any output:
TypeScript
record(params: RecordParams): void
Parameters
The parameters for the record method are defined within the RecordParams type, which supports detailed tracking and rich data collection:
TypeScript
type RecordParams = {
eventTitle: string, // Mandatory title of the event.
accountId?: string, // Optional account ID involved in the event.
userId?: string, // Optional user ID related to the event.
accountAttributes?: {[key:string]: any}, // Optional attributes associated with the account.
userAttributes?: {[key:string]: any}, // Optional attributes specific to the user.
data?: {[key:string]: any} // Optional additional data relevant to the event.
}
Identify
The identify method allows you to tie a user to their actions and record attributes about them. It includes a unique user ID and any optional attributes you know about the user, like their email, name, and more.
Identifying users helps us understand who they are and what they are doing. Once identified, Intempt connects events related to formerly anonymous IDs with the unique set IDs.
Example
JavaScript
function loginRequest(user) {
return authUser(user)
.then(authorizedUser => {
intempt.identify({userId: user.email})
})
}
This usage scenario involves calling the identify function after successfully authenticating the user, ensuring that all subsequent actions are correctly associated with the identified user.
Declaration
The identify method is declared as follows in TypeScript, indicating that it does not return any value:
TypeScript
identify(params:IdentifyParams):void
Parameters
The parameters for the identify method is defined by the IdentifyParams type, which allows for detailed user tracking and event categorization:
TypeScript
type IdentifyParams = {
userId: string,
eventTitle?: string,
userAttributes?:{[key:string]:any}
data?:{[key:string]:any}
}
📘 If you use logOut, we highly recommend using identify.
Group
The group method associates an individual user with a group, such as a company, organization, account, project, or team.
The Group method enables you to identify what account or organization your users are part of. Two IDs are relevant in a Group call: the userId, which belongs to and refers to the user, and the accountId, which belongs to and refers to the specific group. A user can be in more than one group, which would mean different group IDs, but the user will only have one user ID that is associated with each of the different groups.
In addition to the accountId, which is how you’d identify the specific group or company, the group method receives attributes specific to the group, like industry or the number of employees that belong to that specific account. Like the attributes of an identify method, you can update these when you call the same attribute with a different value.
Example
JavaScript
const groupParams = {
accountId: '12345',
eventTitle: 'New User Group',
accountAttributes: {
leader: 'John Doe',
size: 10
}
};
intempt.group(groupParams);
In this example, the group method is used to log information about a new user group, including details about the group leader and size.
Declaration
The group method is declared as follows in TypeScript, indicating that it does not return any value:
TypeScript
group(params:GroupParams):void
Parameters
The parameters for the group method are defined by the GroupParams type, which allows for detailed user tracking and event categorization:
TypeScript
type GroupParams = {
accountId: string,
eventTitle?: string,
accountAttributes?: {[key:string]:any}
}
Alias
The alias method associates two user IDs together, typically when you want to merge multiple profiles or sessions under a unified identity. This method is crucial for maintaining continuity when a user has changed their identification method or has multiple accounts.
Example
JavaScript
const aliasParams = {
userId: 'user123',
anotherUserId: 'user456'
};
intempt.alias(aliasParams);In this example, the alias method associates the user ID 'user123' with another user ID 'user456'. This can help in cases where the same individual has used different login methods or has multiple accounts that need to be treated as a single entity.
Declaration
The alias method is declared as follows in TypeScript, indicating that it does not return any value:
JavaScript
alias(params: AliasParams): void
Parameters
JavaScript
type AliasParams = {
userId: string, // The primary user ID.
anotherUserId: string, // The user ID to be merged with the primary ID.
}
optIn
The optIn method enables tracking of user interactions within an application and reverses any previous tracking restrictions set by the optOut method.
Example
JavaScript
intempt.optIn();
After this method is called, the application will begin to track user activities, assuming no other restrictions are in place.
Declaration
TypeScript
optIn(): void
optOut
The optOut method disables the tracking of user interactions, ensuring that the user's actions are not recorded.
Example
JavaScript
intempt.optOut();
Declaration
TypeScript
optOut(): void
isUserOptIn
The isUserOptIn method checks whether the user has consented to tracking. It is primarily used to ensure compliance with user preferences before performing any tracking operations.
Example
JavaScript
if (intempt.isUserOptIn()) {
console.log("Tracking is enabled.");
} else {
console.log("Tracking is disabled.");
}
This example demonstrates verifying if tracking is enabled before logging or collecting any data.
Declaration
TypeScript
isUserOptIn(): boolean
Returns
Boolean: Returns true if tracking is enabled (optIn has been called) and false if tracking is disabled (
optOuthas been called). The default state is true, indicating that tracking is enabled unless explicitly disabled.
Consent
You can use consent method to track if the user has provided consent to use their data for consent purposes.
This functionality is critical that you only use the data in compliance with privacy regulations like GDPR and CCPA.
Example
JavaScript
const consentParams = {
action: 'agree',
validUntil: 1691823151000, // Unix timestamp for consent expiry
email: '[email protected]',
message: 'User agreed to marketing emails.',
category: 'marketing'
};
intempt.consent(consentParams);
In this example, the consent method logs a user's agreement to receive marketing emails, specifying the duration of the consent and additional details about the consent given.
Declaration
The consent method is declared as follows in TypeScript, showing that it does not produce a return value:
TypeScript
consent(params: ConsentParams): void
Parameters
The parameters for the consent method are specified in the ConsentParams type, which supports comprehensive tracking of consent-related information:
TypeScript
type ConsentParams = {
action: ConsentAction, // The type of action taken (e.g., 'agree', 'decline').
validUntil: number, // Unix timestamp indicating when the consent expires.
email?: string, // Optional: User's email address, if applicable.
message?: string, // Optional: A message detailing the consent scenario.
category?: string // Optional: Category of consent (e.g., 'marketing', 'analytics').
}
Log out
The logOut function is used to clear all stored data from the browser’s storage, including the profile ID. Additionally, the user can manually remove all data stored by Intempt using the browser console.
Example
JavaScript
intempt.logOut()
📘 If you use identify, we highly recommend using logOut as well.
Recommendation
The method allows you to get products from a feed using an ID. Fields and quantity are configurable parameters to select the fields returned in the response and the number of products from the feed. Sending nulls means that all fields will be returned, and the product amount will be limited to 5. The product ID is a nullable parameter, and it's necessary for feeds with product input, like "Purchased Together".
Example
JavaScript
intempt.recommendation({id: 111090, quantity: 5, fields: ["title", "image_url", "price"]})
This example retrieves five recommended products using the feed with ID 111090, including only the title, image URL, and price in the response.
Declaration
JavaScript
recommendation (params:{
id:number,
quantity:number
fields:string[]
}):Promise<any>
Parameters
id (number, required) – The ID of the feed used to generate recommendations.
quantity (number, optional) – The number of recommended products to return. Defaults to 5.
fields (string[], optional) – A list of product attributes to include in the response (e.g.,
["title", "image_url", "price"]).
Returns
A Promise that resolves to an array of recommended products.
This method provides full flexibility in fetching and displaying personalized product recommendations based on predefined feed settings.
SDK provides additional methods for product events
Product Add
The productAdd method emits an event when a product is added to the cart.
Declaration
JavaScript
productAdd(params: {
productId: string,
quantity?: number
}): Promise<void>
Parameters
productId(string, required) - The unique identifier of the product being added to the cart.quantity(number, optional) – The number of units added to the cart.
Returns
A Promise<void> that resolves once the event is emitted.
Example
JavaScript
intempt.productAdd({ productId: "SKU12345", quantity: 1 });
This logs the addition of a product to the shopping cart, triggering an "Added to cart" event.
Product Ordered
The productOrderedmethod emits an event when a list of products is ordered, ensuring all products have valid details.
Declaration
JavaScript
productOrdered(products: {
productId: string,
quantity?: number
}[]): Promise<void>
Parameters
productId(string, required) - The unique identifier of the product being added to the cart.quantity(number, optional) – The number of units added to the cart.
Returns
A Promise<void> that resolves once the event is emitted.
Example
JavaScript
intempt.productOrdered([
{ productId: "SKU12345", quantity: 2 },
{ productId: "SKU16347", quantity: 4 }
]);
This triggers an order event for multiple products.
Product View
The productView method emits an event when a product is viewed by the user.
Declaration
JavaScript
productView(params: { productId: string }): Promise<void>
Parameters
productId(string, required) - The unique identifier of the product being added to the cart.
Returns
A Promise<void> that resolves once the event is emitted.
Example
JavaScript
intempt.productView({ productId: "SKU12345" });
This triggers an event when a product is viewed by the user.
Troubleshooting
1. How do you verify if the event is being tracked?
There are two ways to verify if your events were tracked successfully.
A. Check via the browser console's network tab.
Use the browser's inspect tool, select the network tab, and enter "track" into the search bar.
This will only show network events related to event tracking via Intempt.
If the request is successful (returns 200 or 201), the event was tracked successfully. You can verify this by clicking on the "Payload" tab.
B. Check via your project user list.
You can visit your project user list and check the latest user data.
If under "Event stream," it matches the event performed, it means it was tracked successfully.
2. Why aren't my events showing up in Intempt?
Make sure you've disabled ad blockers and your Do Not Track (DNT) browser settings are set to false when testing your JavaScript implementation. If the DNT setting is set to true, then Intempt won't collect information from that Intempt project.
Double-check if you are using the correct event listeners. You need to use event listeners to track each custom event when it occurs. First, you need to use a specific HTML element (<input>, <button>, etc.) and add an event listener to it. Then, you can include the custom event you define in the following example.
HTMLJavaScript
<button id="regBtn">Sign up</button>
🚧 Don't miss out!
Make sure that you use a unique ID values for HTML elements that you are using.
3. Does Intempt use third-party cookies?
No, our Intempt JavaScript SDK does not set or use any third-party cookies.
4. Field Type Validation
When sending custom events, each field must match the data type defined in your event schema. If a field’s type changes (e.g., from a string to an object), the event will be rejected. This ensures data consistency and prevents errors. Example: If the field name is defined as a string in the schema:
const event = { name: “John Doe” }; // ✅ Accepted const event = { name: { first: “John”, last: “Doe” } }; // ❌ Rejected
What to do? Always ensure that event fields retain the same type as defined in your schema.
Adding New Fields to Custom Events You can now safely add new fields to your custom event schema without impacting existing fields. This allows you to extend your event-tracking capabilities while keeping previous fields intact and functional. Example:
Original event - After adding a new field
const event = { name: “John Doe” }; // ✅ Accepted const event = { name: { first: “John”, last: “Doe” } }; // ❌ Rejected
Existing fields will remain usable even after schema updates.





