Skip to main content
sdk

Web SDK Reference

draft
Audience: developerUpdated 2026-07-26

Getting Started​

Use the Binoban.js QuickStart Guide to learn how to add Binoban.js to your site. Once you’ve installed the library, read on for the detailed API reference.

Basic tracking methods​

The basic tracking methods below serve as the building blocks of your Binoban tracking. They include Identify, Track, Page.

For any of the methods described in this page, you can replace the properties in the code samples with variables that represent the data collected.

Identify​

Use the identify method to link your users and their actions, to a recognizable userId and traits.

Identify calls and anonymous visitors

Binoban recommends against using identify for anonymous visitors to your site. Binoban.js automatically retrieves an anonymousId from localStorage or assigns one for new visitors, and then attaches it to all page and track events both before and after an identify.

The Identify method follows the format below:

Binoban.identify([userId], [traits], [options], [callback]);

The Identify call has the following fields:

FieldTypeDescription
userIdoptionalStringThe database ID for the user. If you don't know who the user is yet, you can omit the userId and just record traits.
traitsoptionalObjectA dictionary of traits you know about the user, like email or name.
optionsoptionalObjectA dictionary of options. for the call. Note: If you do not pass a traits object, pass an empty object (as an {}) before options.
callbackoptionalFunctionA function executed after a timeout of 300 ms, giving the browser time to make outbound requests first.

By default, Binoban.js caches traits in the browser's localStorage and attaches them to each Identify call.

For example, you might call Identify when someone signs up for a newsletter but hasn't yet created an account on your site. The example below shows an Identify call (using hard-coded traits) that you might send in this case.

Binoban.identify({
nickname: "Amazing Denis",
favoriteCompiler: "C",
industry: "Computer Science",
});

Then, when the user completes the sign up process, you might see the following:

Binoban.identify("1234-xyz", {
name: "Dennis Ritchie",
email: "denis@c-language.org",
});

The traits object for the second call also includes nickname, favoriteCompiler, and industry.

You may omit both traits and options, and pass the callback as the second argument.

Binoban.identify("1234-xyz", function () {
// Do something after the identify request has been sent
});

Track​

The Track method lets you record actions your users perform. ou can see a track example in the Quickstart guide

The Track method follows the format below:

Binoban.track(event, [properties], [options], [callback]);

The track call has the following fields:

FieldTypeDescription
eventStringThe name of the event you're tracking.
propertiesObjectOptional. A dictionary of properties for the event. If the event was 'added_to_cart', it might have properties like price and productType.
optionsObjectOptional. A dictionary of options. Note: If you do not pass a properties object, pass an empty object (like {}) before options.
callbackFunctionOptional. A function that runs after a timeout of 300 ms, giving the browser time to make outbound requests first.

The only required argument in Binoban.js is an event name string.

Example Track call:

Binoban.track("article_completed", {
title: "How to Create a Tracking Plan",
course: "Intro to binoban",
});

The only required argument on Track calls in Binoban.js is an event name string.

trackLink is a helper method that attaches a Track call as a handler to a link. When a user clicks the link, trackLink delays the navigation event by 300ms before proceeding, ensuring the Track request has enough time to send before the page starts unloading.

This is useful when a page redirects too quickly, preventing the Track method from completing all requests. By momentarily holding off navigation, trackLink increases the likelihood that tracking data reaches Binoban and destinations successfully.

The trackLink method follows the format below:

Binoban.trackLink(element, event, [properties]);
FieldTypeDescription
element(s)Element or ArrayDOM element to bind with track method. You may pass an array of elements or jQuery objects. Note: This must be an element, not a CSS selector.
eventString or FunctionThe name of the event, passed to the track method. Or a function that returns a string to use as the name of the track event.
propertiesoptionalObject or FunctionA dictionary of properties to pass with the track method or a function that returns an object to use as the properties of the event.

Example:

var link = document.getElementById("free-trial-link");

Binoban.trackLink(link, "clicked_free_trial_link", {
plan: "Enterprise",
});

Track form​

trackForm is a helper method that binds a track call to a form submission. The trackForm method inserts a timeout of 300 ms to give the track call more time to complete. This is useful to prevent a page from redirecting before the track method could complete all requests.

The trackForm method follows the format below.

Binoban.trackForm(form, event, [properties]);
FieldTypeDescription
form(s)Element or ArrayThe form element to track or an array of form elements or jQuery objects. Note: trackForm takes an element, not a CSS selector. Binoban recommends that you wait until the DOM loads before passing the form element.
eventString or FunctionThe name of the event, passed to the track method. Or a function that returns a string to use as the name of the track event.
propertiesoptionalObject or FunctionA dictionary of properties to pass with the track method. Or a function that returns an object to use as the properties of the event.

Example:

var form = document.getElementById("signup-form");

Binoban.trackForm(form, "signed_up", {
plan: "Premium",
revenue: 99.0,
});

Page​

The Page method lets you record page views on your website, along with optional extra information about the page viewed by the user.

Because some Destinations require a page call to instantiate their libraries, you must call page at least once per page load. You can call it more than once if needed, for example, on virtual page changes in a single page app.

Binoban.js includes a Page call by default as the final line in the Binoban.js snippet. You can update this page call within the guidelines below.

The page method follows the format below.

Binoban.page([category], [name], [properties], [options], [callback]);

The page call has the following fields:

FieldTypeDescription
categoryoptionalStringThe category of the page. Useful for cases like ecommerce where many pages might live under a single category. Note: if you pass only one string to page it is assumed to be name. You must include a name to send a category.
nameoptionalStringThe name of the page.
propertiesoptionalObjectA dictionary of properties of the page. Note: Binoban.js collects url, title, referrer and path are automatically. This defaults to a canonical url, if available, and falls back to document.location.href.
optionsoptionalObjectA dictionary of options. Note: If you do not pass a properties object, pass an empty object (like {}) before options.
callbackoptionalFunctionA function that runs after a timeout of 300 ms, giving the browser time to make outbound requests first. However, this function might not execute if one of the device-mode libraries has been blocked from loading.

Default page properties​

Binoban.js adds properties to each page call.

Binoban.page("Pricing");

Binoban adds the following information:

Binoban.page("Pricing", {
title: "example Pricing",
url: "https://example.com/pricing",
path: "/pricing",
referrer: "https://example.com/warehouses",
});

You can override these values by explicitly setting them in your calls. For example:

Binoban.page("Pricing", {
title: "My Overridden Title",
path: "/pricing/view",
});

Translates to:

Binoban.page("Pricing", {
title: "My Overridden Title",
url: "https://example.com/pricing",
path: "/pricing/view",
referrer: "https://example.com/warehouses",
});

Binoban sets the path and url property to the value of the canonical element on your page. If a canonical element is not set, the values will be set from the browser.

Utility methods​

The Binoban.js utility methods help you change how Binoban loads on your page. They include:

Ready​

The ready method lets you pass in a method that gets called after Binoban.js finishes initializing and after all internal settings load. It's like jQuery's ready method

Note: window.Binoban.initialized is a simple boolean, not an event or a pub/sub system. This means you can't subscribe to changes in its value. If you need to detect when it changes from false to true, you must set up a polling mechanism to monitor the value.

The code in the ready function only executes after ready is emitted.

Binoban.ready(() => {
console.log("Binoban is ready!");
});

The ready method uses the following format:

Binoban.ready(callback);

The ready method has the following fields:

FieldTypeDescription
callbackFunctionA function to be executed after all enabled destinations have loaded.

Debug​

Calling the debug method turns on debug mode, which logs helpful messages to the console. Subsequent Binoban events generate messages in the developer console after you invoke debug.

Enable:

Binoban.debug(true);

Disable:

Binoban.debug(false);

Emitter​

The global binoban object emits events whenever you call identify, track, or page.

Use the on method to set listeners for these events and run your own custom code. This can be useful if you want to send data to a service for which Binoban doesn't have a destination.

Binoban.on(method, callback);
FieldTypeDescription
methodStringName of the method to listen for.
callbackFunctionA function to execute after each emitted method, taking three arguments: event, properties, options.

Example:

Binoban.on("track", (event, properties, options) => {
bigdataTool.push(["recordEvent", event]);
});

This method emits events before they are processed by the Binoban integration, and may not include some of the normalization Binoban performs on the client before sending the data to the Binoban servers.

info

Page event properties are stored in the options object.

Extending timeout​

The timeout method sets the length (in milliseconds) of callbacks and helper functions. This is useful if you have multiple scripts that need to fire in your callback or trackLink, trackForm helper function.

The example below sets the timeout to 500 ms.

Binoban.timeout(500);

success "Tip" If you're triggering ad network conversion pixels, Binoban recommends extending timeout to 500 ms to account for slow load times.

Reset or log out​

Calling reset resets the id, including anonymousId, and clears traits for the currently identified user and group.

Binoban.reset();

The reset method only clears the cookies and localStorage created by Binoban. It doesn't clear data from other integrated tools, as those native libraries might set their own cookies to manage user tracking, sessions, and manage state. To completely clear out the user session, see the documentation provided by those tools.

Binoban doesn't share localStorage across subdomains. If you use Binoban tracking on multiple subdomains, you must call Binoban.reset() for each subdomain to completely clear out the user session.

Trace sessions​

A trace session is a short-lived, opt-in window during which every event carries a traceSessionId, and the SDK records what happened to each upload. For the full task — including where session codes come from and how to read the delivery log — see Trace a visitor.

Binoban.joinTrace('k4rq-8w2m-h7bd');     // start, using the code the panel issues
Binoban.leaveTrace(); // end it now
Binoban.activeTraceSessionId(); // 'k4rq-8w2m-h7bd', or null when none is active
Binoban.traceDeliveryLog(); // the recorded upload outcomes, oldest first

joinTrace and leaveTrace can also be called before the SDK has finished loading — they are queued and replayed like track and identify. The two read methods cannot, because a queued call has no return value to give you; call those after ready().

A session id is 8 to 64 characters of A-Z a-z 0-9 - _. Whitespace and letter case do not matter — the code is trimmed and lowercased, so the id you read back is the lowercase form. A malformed id is reported to the console and ignored rather than thrown.

A trace also starts from the page URL, with no call at all:

https://shop.example.com/checkout?bnb_trace=k4rq-8w2m-h7bd

The parameter is read once during startup, so the first event of the page load already carries the session. The session survives navigation, ends after 12 hours or 250 events whichever comes first, and is not written to localStorage at all when disableClientPersistence is set.

reset() does not end a trace. It clears identity; a trace is diagnostics, and one often needs to outlive a sign-out.

Retries​

Binoban.js automatically retries sending events when there are network or server errors. This helps reduce data loss in cases where the user is offline or the Binoban API is temporarily unavailable.

When retries are enabled, Binoban.js can:

  • Track users offline. Events get stored locally and sent once the user comes back online.
  • Handle intermittent network issues. Events are queued and retried until they’re successfully delivered.

Here's how retries work:

  • Events are stored in localStorage when available, with an in-memory fallback.
  • Binoban.js retries up to 10 times, with increasing backoff intervals between attempts.
  • A maximum of 100 events can be queued to avoid using too much local storage.

What is retried, and what is not​

Not every failure is worth retrying, and the SDK distinguishes them:

ResponseRetriedReported as
5xx server erroryes, with backofffailed
429 rate limitedyes, after the interval the server asks forfailed
No response at all (offline, blocked, dead host)yesfailed
4xx refusal other than 429nofailed

A 4xx other than 429 means the server understood the request and refused it — a validation error, an unknown source, a bad credential. That refusal is permanent, so retrying it would turn one bad event into ten identical rejected requests against your own deployment. The event is reported as failed and dropped.

Changed behaviour

Earlier versions of the Web SDK treated a 4xx refusal as a successful delivery: the response body was never read, and the event was announced as delivered. Anything you have built on the SDK's delivery events will now see a rejected event reported as a failure rather than a success. That is the correct answer arriving late, but it is a change — see the release notes.

To see why an event was refused, read the trace delivery log; the reason exists nowhere else.

UTM Tracking​

UTM parameters are only used when linking to your site from outside your domain. When a visitor arrives using a link containing UTM parameters, Binoban's WebSDK library will parse the URL query string and add the information to the event payload.

UTM parameters contain three essential components (utm_source, utm_medium, utm_campaign) and two optional (utm_content, utm_term). For example, if you include the following three parameters in your URL: ?utm_source=mysource&utm_medium=email&utm_campaign=mytestcampaign, once a visitor arrives using a link containing the above, Binoban automatically grabs the UTM parameters and subsequent events will contain these parameters within the 'context' object (visible in the raw view of your Source Debugger.)

So, for example, if somebody follows the link with above query string to your site, the subsequent 'page' call in your Debugger should contain the below and will be passed to any enabled destinations:

"context": {
"campaign": {
"medium": "email",
"name": "mytestcampaign",
"source": "mysource",
},

Whenever the UTM parameters are no longer a part of the URL, Binoban no longer includes them. For example, if the user goes to a new page within your website which does not contain these parameters, they will not be included in subsequent events. UTM parameters are non-persistent by default as they could potentially cause data accuracy problems. Here's an example of why: Say a user clicks on an ad and lands on your site. He navigates around and bookmarks an internal page - or maybe shares a link with a friend, who shares it with another friend. All those links would then point back to the same test utm_source as the initial referrer for any purchase.

Binoban doesn't validate UTM parameter names. This design supports the flexibility to track both standard parameters (for example, utm_source, utm_medium) and custom parameters defined by users. As a result, all parameters present in the URL collected as is, and are added to the context field without checks for naming conventions or validity.

If you want to ensure that only standard UTM parameters (such as, utm_source, utm_medium, utm_campaign, utm_content, utm_term) are included in the context.campaign object, you can implement Source middleware in your Binoban.js setup.

For example:

window.Binoban.addSourceMiddleware(({ payload, next }) => {
if (payload.obj.context?.campaign) {
const allowedFields = ["source", "medium", "term", "campaign", "content"];
const campaign = payload.obj.context.campaign;
Object.keys(campaign).forEach((key) => {
if (!allowedFields.includes(key)) {
delete campaign[key];
}
});
}
next(payload);
});

This middleware filters out any non-standard parameters from the context.campaign object before they're sent to Binoban or forwarded to your enabled destinations.

Binoban.js performance​

The Binoban.js library is loaded with the HTML script async tag. This also means that Binoban fires methods asynchronously, so you should adjust your code accordingly if you require that events be sent from the browser in a specific order.

info

Binoban.js doesn't set third-party cookies and only sets first-party cookies.

Cookies set by Binoban.js​

Binoban sets three cookies in general:

CookieDescription
bob_anonymous_idAn anonymous ID generated by Binoban.js, used for Binoban calls.
bob_user_idA user ID that can be specified by making an identify() call with Binoban.js.

For Google Chrome, these cookies expire by default one year after the date created. Other supported browsers might have a different expiration time.

Some user/group traits are also stored in localStorage:

CookieDescription
bob_user_traitsThe traits that are passed in an identify() call.

Note that localStorage variables don't expire because the browser defines that functionality.

Local storage cookies used by Binoban.js​

Binoban.js uses localstorage cookies if you have retries enabled, to keep track of retry timing.

  • The ack cookie is a timer used to see if another tab should claim the retry queue.
  • The reclaimStart and reclaimEnd cookies determine if a tab takes over the queue from another tab.
  • The inProgress and queue cookies track events in progress, and events queued for retry.

You can set the debug cookie to Binoban.js to log debug messages from Binoban.js to the console.

Page context privacy​

Binoban.js reads the browser's location to fill in the context.page object on every event. On most sites that is harmless. On a site whose URLs carry credentials — an SSO callback, an OAuth redirect, a password-reset link — it means those credentials are forwarded to Binoban and on to every enabled destination.

The privacy load option bounds what the SDK is allowed to collect from the location.

What it governs​

FieldGovernedHow
context.page.urlyesreduced to origin + pathname + kept query
context.page.searchyesfiltered to the kept parameters
context.page.pathyeswhen it comes from a <link rel="canonical"> carrying a query
context.page.referreryessee referrer below
context.page.titlenonot derived from the location
context.page.originnoalready just the origin

The same policy also applies to the URL and referrer sent on retail-media ad requests, to the url argument of analytics.pageview(url), and to url values read out of a publisher's JSON-LD product schema.

The URL fragment is always dropped, at every level. OAuth's implicit grant returns #access_token=…, so the fragment is never collected regardless of how you configure the options below.

Options​

{
privacy: {
pageContext: "sanitized",
queryAllowlist: ["promo_id"],
queryDenylist: ["reset_key"],
referrer: "origin"
}
}
OptionAccepted valuesDefault
pageContext"sanitized" | "full"see Which default you actually get
queryAllowliststring[]["btid", "urid"], plus every utm_-prefixed key
queryDenyliststring[]the 19 credential-shaped names listed below
referrer"origin" | "full" | "none"derived from pageContext

An unrecognized value is not an error: the SDK logs a [binoban] console warning and falls back to the safe option ("sanitized" for pageContext, the derived value for referrer). A queryAllowlist or queryDenylist that isn't an array is warned about and ignored, leaving the defaults in place.

pageContext​

This is the only option that changes which of the two lists is consulted. Setting it wrong is the usual reason a list appears to do nothing.

"sanitized" — an allowlist. A query parameter is kept only if it is explicitly permitted. Everything else is dropped, including parameters nobody anticipated. A parameter is kept when it either:

  • begins with utm_ — a prefix rule, not a fixed list, so utm_id and any future utm_* key are covered; or
  • appears in queryAllowlist (which already contains btid and urid).

https://shop.example/checkout?utm_source=email&btid=42&session=a1b2&ref=x#tok becomes https://shop.example/checkout?utm_source=email&btid=42.

"full" — a denylist. Every query parameter is kept except those named in queryDenylist. The same URL becomes https://shop.example/checkout?utm_source=email&btid=42&ref=x — session is denylisted, the fragment is still dropped, but ref survives because nothing said to drop it.

A denylist can only catch names somebody thought of, so "full" is not a safety floor — it is an opt-out of sanitizing with a backstop. Choose it only if you are certain your URLs never carry credentials.

The default queryDenylist:

token, code, jwt, access_token, id_token, refresh_token, auth, authorization, session, sid, secret, password, passwd, pwd, api_key, apikey, sig, signature, state

code and state are on that list deliberately: together they are an OAuth authorization code exchange. A bare key is deliberately not on it — too vague a name to drop silently, and api_key/apikey already cover the credential case.

queryAllowlist and queryDenylist​

The pairing is what trips people up:

You setConsulted under "sanitized"Consulted under "full"
queryAllowlistyes — adds parameters to keepno
queryDenylistnoyes — adds parameters to drop

Setting queryAllowlist while running at "full" has no effect, and vice versa. Both lists are safe to set together if you switch levels per environment.

Three properties hold for both:

  • They extend the defaults; they never shrink them. You cannot configure utm_*, btid, or urid out of the allowlist, and you cannot remove a name from the denylist. This is intentional — a customer trimming the allowlist to "just what we need" would silently break their own campaign attribution.
  • Entries are exact key names, not patterns. "promo" does not match promo_id. The only prefix rule in the system is the built-in utm_.
  • Matching is case-insensitive. "Session", "SESSION" and "session" are the same entry.

referrer​

document.referrer deserves its own control because on an OAuth flow the referrer is the identity provider's authorize URL, credentials and all.

ValueResult
"origin"only the referrer's origin, e.g. https://accounts.example.com
"full"the full referrer, still filtered by the level's query policy
"none"context.page.referrer is always an empty string

If you do not set it, it is derived from pageContext: "sanitized" gives "origin", and "full" gives "full". Setting referrer explicitly always wins over that derivation, at either level.

Note that "full" here is not a bypass. It still runs the active query policy over the referrer, so an OAuth code in an identity provider's referrer is caught by the denylist even at the most permissive combination of settings.

Which default you actually get​

The SDK's own built-in fallback is "sanitized" — an unconfigured SDK fails closed.

However, the bundle Binoban builds for your deployment can carry its own built-in default, fixed at build time. Bundles currently ship with "full", which preserves the collection behavior from before these options existed, so that an SDK upgrade never silently changes the data already flowing into your warehouse.

Precedence is, first match wins:

  1. the privacy.pageContext value you pass to load()
  2. the default compiled into your deployment's bundle
  3. the SDK's built-in "sanitized"

Because of step 2, do not rely on the default — pass pageContext explicitly if the level matters to you. To check what your bundle does without configuring anything, load a page with a junk query parameter and inspect context.page.url on the resulting event in your Source Debugger: if the parameter survived, you are running at "full".

Interaction with UTM tracking​

UTM Tracking above describes parameters being collected as-is. That holds at "full". At "sanitized", only utm_-prefixed keys and your allowlist survive to reach context.campaign — which is why the utm_ prefix rule is built in and cannot be configured away.

Behavior on malformed input​

Every sanitizing function fails closed. If a URL or referrer cannot be parsed, the field is emitted as an empty string rather than passed through unchanged. An unparseable URL is exactly where an unusual value shows up, so returning the input on error would be a policy bypass.

Setting it​

With the npm package, privacy is part of the typed config:

import { createBinoban } from "@binoban/web-sdk";

export const binoban = createBinoban({
credentials: { apiKey: "…", sourceIdentifier: "…" },
host: { sdkPath: "…", apiPath: "…", rtbPath: "…", metricPath: "…" },
privacy: {
pageContext: "sanitized",
queryAllowlist: ["promo_id"],
referrer: "origin",
},
});

With the snippet, add it to the load() call:

_SDK.load({
credentials: { apiKey: "PROJECT_API_KEY", sourceIdentifier: "…" },
host: { sdkPath: "…", apiPath: "…", rtbPath: "…", metricPath: "…" },
privacy: { pageContext: "sanitized", referrer: "origin" }
});

The policy is resolved once, when the SDK loads, and cannot be changed afterwards. Events queued by the snippet before the SDK arrives are still covered: the snippet captures the location at call time, and the SDK applies the policy to those captured values when it drains the queue. You do not need to change an already-deployed snippet to get this.

Tracking Blockers and Browser Privacy Settings​

Binoban does not endorse bypassing tracking blockers or browser privacy settings for client-side tracking. Your users have control over what gets loaded on their pages and can use plugins or browser settings to block third-party scripts, including Binoban. To minimize client-side data loss, Binoban recommends you choose from the following routes:

  1. Respect the user's decision to implement tracking blockers or use privacy settings, knowing that, unfortunately, some data will be lost.
  2. Ask the customer to disable the tracking blockers or adjust their privacy settings (for example, in the case of large, corporate customers).
  3. Move as many events and tracking actions as possible to a server-side library, which won't encounter the same limitations.

Installing from npm does not avoid blockers​

A common assumption is that installing @binoban/web-sdk from npm bundles the SDK into your application, putting it beyond a blocker's reach. It does not.

The npm package is a loader. It injects a <script> tag pointing at your host.sdkPath and queues your calls until that script arrives — exactly what the inline snippet does, with types and without the copy-paste. The bundle is still fetched over the network at runtime and is blockable on the same terms.

What genuinely helps is something you already have: Binoban is deployed per-customer, so the SDK is served from your own host (for example static.example.com/sdk/web/binoban.js) rather than a shared analytics domain. Blocklists are built from well-known third-party hostnames, so a first-party host is far less likely to appear on one. That property comes from the deployment model and applies to both installation options equally.

Two consequences worth planning around:

  • Events queued before a blocked script are lost, not delayed. Both options buffer calls in memory while the bundle loads. If the bundle never arrives, the buffer is never drained.
  • ready() never fires when the bundle is blocked, so do not gate anything your page needs — navigation, rendering, form submission — behind it.

Global namespace​

However you install it, the SDK attaches to a global whose name is recorded in window.__GLOBAL_CDXP_SDK_KEY — 'Binoban' unless you changed it. Reference it by that name if you need to reach the instance directly.

With the npm package, prefer the object createBinoban() returned: it is typed, and it keeps working across the moment the bundle loads and replaces the global. Reach for the global only for code you cannot route through that object, such as a third-party script sharing the page.

Identity​

This section explains how Binoban.js identifies users, and passes userID and anonymousID data, and how to override and change this information.

Binoban ID Persistence​

To ensure high fidelity, first-party customer data, Binoban writes the user's IDs to the user's local storage, and uses that as the Binoban ID on the cookie whenever possible. Local Storage is meant for storing this type of first-party customer information.

If a user returns to your site after the cookie expires, Binoban.js looks for an old ID in the user's localStorage, and if one is found, sets it as the user's ID again in the new cookie. If a user clears their cookies and localstorage, all of the IDs are removed, and the user gets a completely new anonymousID when they next visit the page.

Anonymous IDs​

Binoban.js generates a universally unique ID (UUID) for the viewer during the library's initialization phase, and sets this as anonymousId for each new visitor to your site.

Example:

bob_anonymous_id=%2239ee7ea5-b6d8-4174-b612-04e1ef3fa952

You can override the default-generated anonymousID in code using the methods described below:

Retrieve the Anonymous ID​

You can get the user's current anonymousId using the following call:

Binoban.user().anonymousId();

If the user's anonymousId is null (meaning not set) when you call this function, Binoban.js automatically generated and sets a new anonymousId for the user.

Refreshing the Anonymous ID​

A user's anonymousId changes when any of the following conditions are met.

  • The user clears their cookies and localstorage.
  • Your site or app calls Binoban.reset() during in the user's browser session.
  • Your site or app calls Binoban.identify() with a userId that is different from the current userId.
  • Your site or app is setting bob_user_id to an empty string or calling Binoban.user().id('') before calling Binoban.identify(). This sequence of events will result in a new anonymousId being set when Binoban.identify() is called.

Override the Anonymous ID from the Binoban snippet​

You can also set the anonymousId immediately inside your Binoban snippet, even before the ready method returns.

Binoban.setAnonymousId("ABC-123-XYZ");

Use this method if you are queueing calls before ready returns and they require a custom anonymousId. Keep in mind that setting the anonymousId in Binoban.js does not overwrite the anonymous tracking IDs for any destinations you're using.

Override the default Anonymous ID with a call​

If the default generated UUID does not meet your needs, you can override it anonymousId for the current user using either of the following methods.

Binoban.user().anonymousId("ABC-123-XYZ");
Binoban.setAnonymousId("ABC-123-XYZ");

These methods behave exactly the same.

Override the Anonymous ID using the options object​

Or in the options object of identify, page, or track calls, like this:

Set the anonymousId in the Options object using the format in the following examples.

The custom anonymousId persists when you use these methods, even if you do not explicitly specify the anonymousId in the calls.

For example, after the Track call below sets the anonId, any later track calls from this user will have the anonymousId of ABC-123-XYZ, even if it is not explicitly specified in the track call.

Override anonymousId in an Identify call​
Binoban.identify(
"user_123",
{
name: "Jane Doe",
},
{
anonymousId: "ABC-123-XYZ",
}
);
Override anonymousId on a Page call​
Binoban.page({}, { anonymousId: "ABC-123-XYZ" });
Override anonymousId on a Track call​
Binoban.track(
"email_clicked",
{
callToAction: "Signup",
},
{
anonymousId: "ABC-123-XYZ",
}
);

Saving traits to the context object​

Traits are individual pieces of information that you know about a user, and which can change over time.

The options dictionary contains a sub-dictionary called context which automatically captures data depending on the event- and source-type.

The context object contains an optional traits dictionary that contains traits about the current user. You can use this to store information about a user that you got from previous Identify calls, and that you want to add to Track or Page events.

success

The traits object in options.context.traits does not cause anonymousId to persist across different calls.

Consider this Identify event:

Binoban.identify("12091906-01011992", {
plan_id: "Paid, Tier 2",
email: "grace@example.com",
});

The "trait" on this event is plan_id. You can pass these traits into context.traits, so you can use them in Track or Page events that the user triggers later.

The example below shows how you could pass the plan_id as a trait so you can use it later.

Binoban.track(
"clicked_email",
{
emailCampaign: "First Touch",
},
{
traits: {
plan_id: "Paid, Tier 2",
},
}
);

This appends the plan_id trait to this Track event. This does not add the name or email, since those traits were not added to the context object. You must do this for every following event you want these traits to appear on, as the traits object does not persist between calls.

By default, non-Identify events (like Track or Page) don't automatically collect user traits from previous Identify calls. To include traits from an identify() event in later events, you'll need to add them manually to the context.traits object within the options parameter.

Each Binoban.js method has an options parameter where you can pass the context.traits object, but each method has a specific format.

Clearing Traits​

You can pass an empty object to the traits object to clear all cached traits for a User or Group.

Traits are cached by default when you call the Identify method. You can clear the traits object for the user by passing traits an empty object:

Binoban.user().traits({});

Using Binoban.user()​

You can use the user method as soon as the Binoban.js library loads, to return information about the currently identified user or group. This information is retrieved from the user's cookie.

success

Tip: You can wrap any reference to user() in a ready function block to ensure that Binoban.js has fully loaded so these methods are available.

Examples:

Binoban.ready(function () {
var user = Binoban.user();
var id = user.id();
var traits = user.traits();
});
Binoban.ready(function () {
var group = Binoban.group();
var id = group.id();
var traits = group.traits();
});

Push notifications​

Web push is delivered through Firebase Cloud Messaging and rendered by Binoban's service worker, binoban-messaging.js. For the step-by-step integration see Web push.

Registering a browser​

There is no dedicated method. Track the token Firebase gives you:

Binoban.track('notification_registered', { key: token })

The SDK's push plugin rewrites this event to bb_notification_registered and adds sdk: "WEB" and the current device_id before it is sent. That renamed event is what marks the browser reachable. See Push events.

Call it again on every token refresh.

What the service worker handles​

binoban-messaging.js is deployed by Binoban to your infrastructure; you load it from your own service worker with importScripts. Once registered it:

  • displays the notification using the payload's title, body, icon, image, and badge, honouring requireInteraction;
  • reports delivered on display, and failed if the browser refuses to display;
  • renders up to two action buttons — browsers without notification-action support ignore them;
  • reports clicked with the button index and resolved target URL, then focuses an already-open tab for that URL or opens a new window;
  • reports closed on dismissal;
  • falls back to your site when a payload carries no target.

It ignores any payload whose source is not "binoban", so it coexists with your own push handling.

Limits​

  • No subscribe() helper. Requesting permission and registering the worker are your app's — they are ordinary browser APIs, and consent UX is a site decision.
  • customData is not read on the web. It is available on the native SDKs only; carry context in the target URL instead.
  • Two action buttons on the web, against three on native.

Advanced​

Tracking in Webview​

if you have an Android or iOS App that load your web site in web view, and want to track app users with our web sdk, you should provide android and ios specific credential during initialization

// Load SDK with your key, which will automatically
// load the tools you've enabled for your account. Boosh!
_SDK.load({
credentials: {
apiKey: "PROJECT_WEB_API_KEY",
sourceIdentifier: "PROJECT_WEB_SOURCE_IDENTIFIER",
},
host: {
rtbPath: "YOUR_BINOBAN_SERVER_RTB_URL",
sdkPath: "YOUR_BINOBAN_SERVER_SDK_URL",
apiPath: "YOUR_BINOBAN_SERVER_API_URL",
},
//<--------------- HERE --------------->
mobileApp: {
loadedInWebview: true,
androidCredentials: {
apiKey: "PROJECT_ANDROID_API_KEY",
sourceIdentifier: "PROJECT_ANDROID_SOURCE_IDENTIFIER",
},
iosCredentials: {
apiKey: "PROJECTE_IOS_API_KEY",
sourceIdentifier: "PROJECT_IOS_SOURCE_IDENTIFIER",
},
},
});
info

please note that you should loadedInWebview to true if your web app is in mobile view and set it to false if not.

if you want to enable Binoban Cookie Syncing mechanism with Ad Networks like mediaAd and Yekta Neet, you should pass these options to sdk (during initialization)

// Load SDK with your key, which will automatically
// load the tools you've enabled for your account. Boosh!
_SDK.load({
credentials: {
apiKey: "PROJECT_API_KEY",
sourceIdentifier: "PROJECT_SOURCE_IDENTIFIER",
},
host: {
rtbPath: "YOUR_BINOBAN_SERVER_RTB_URL",
sdkPath: "YOUR_BINOBAN_SERVER_SDK_URL",
apiPath: "YOUR_BINOBAN_SERVER_API_URL",
},
//<--------------- HERE --------------->
cookieSync: {
mediaAd: true,
yektanet: true,
yektanetId: "YOUR_YEKTANET_ID",
},
});
info

you should replace YOUR_YEKTANET_ID with your project specific ID that will provided for you by our support team.