API

The following API allows the user to:

  • track page views
  • track visits on multiple domains and subdomains
  • track e-commerce events (successful orders, cart changes, product and category views)
  • track content impressions
  • manage custom variables to use them later
  • track clicked links to external domains and download files

Command queue

Code snippet with tracking code sets up globally accessible command queue _paq. Users can issue commands by pushing them onto the command queue with _paq.push function. This is the recommended method of calling tracking functions.

_paq.push(command)

Issues a command, e.g. track page view, custom event, site search etc.

Arguments:
  • command (Array<string>) – Array containing a tracking function’s name followed by its arguments. The number of arguments and their meaning are determined by the tracking function.

Example of usage (tracking a custom event by pushing a command to the command queue):

_paq.push(["trackEvent", "video", "video-paused", "intro.mp4", 15.2]);

Commands pushed onto the command queue will be executed once the JavaScript Tracking Client loads. After that, _paq.push becomes synchronous, meaning each command is executed at the moment of push.

JavaScript Tracking Client object

JavaScript Tracking Client object offers an alternative method of calling tracking functions. While it’s more difficult to access than the command queue, it allows to read the return value of a tracking function and makes multi-tracker setups possible.

JavaScript Tracking Client object can be accessed using Piwik.getTracker or Piwik.getAsyncTracker function.

Piwik.getTracker(trackerUrl, siteId)

Getter for JavaScript Tracking Client object.

Arguments:
  • trackerUrl (string) – Required URL for JavaScript Tracking Client
  • siteId (string) – Required Site ID that will be linked to tracked data.
Returns:

JavaScript Tracking Client object

Example of usage (accessing JavaScript Tracking Client object and tracking a custom event):

var jstc = Piwik.getTracker("https://example.com/", "45e07cbf-c8b3-42f3-a6d6-a5a176f623ef");
jstc.trackEvent("video", "video-paused", "intro.mp4", 15.2);

To access internal JavaScript Tracking Client object used for asynchronous tracking you must use the Piwik.getAsyncTracker.

Piwik.getAsyncTracker(trackerUrl, siteId)

Getter for JavaScript Tracking Client instance.

Arguments:
  • trackerUrl (string) – Required URL for JavaScript Tracking Client
  • siteId (string) – Required Site Id that will be linked to tracked data.
Returns:

JavaScript Tracking Client instance

Example of usage (accessing JavaScript Tracking Client object and tracking a custom event):

var jstc = Piwik.getAsyncTracker("https://example.com/", "45e07cbf-c8b3-42f3-a6d6-a5a176f623ef");
jstc.trackEvent("video", "video-paused", "intro.mp4", 15.2);

JavaScript Tracking Client object is also accessible through this keyword in a special command pushed to command queue, where the first element of the command array is a custom function.

_paq.push([function () {
    // *this* is a JavaScript Tracking Client object
    this.addEcommerceItem("01725334", "USB-C chord")
    console.log(this.getEcommerceItems());
}]);

Warning

JavaScript Tracking Client object can’t be accessed before JavaScript Tracking Client file loads (usually a ppms.js file).

Tracking functions

Tracking functions collect and send data to Collecting & Processing Pipeline. They can be called on a JavaScript Tracking Client object or pushed to the command queue as commands.

Page views

trackPageView([customPageTitle])

Tracks page view of the page that the function was run on.

Arguments:
  • customPageTitle (string) – Optional Custom page title, used only for this event

Example of usage:

_paq.push(["trackPageView"]);
jstc.trackPageView();

Note

To overwrite page title for all events that will happen on the page (until a reload), use setDocumentTitle function.

Note

trackPageView is included in the default JavaScript Tracking Client setup snippet. It’s likely you’re already using it.

Custom events

trackEvent(category, action[, name[, value[, dimensions]]])

Tracks custom event, e.g. when visitor interacts with the page.

Arguments:
  • category (string) – Required Event category
  • action (string) – Required Event action
  • name (string) – Optional Event name
  • value (number) – Optional Event value
  • dimensions (object) – Optional Custom dimensions to pass along with the custom event

Example of usage (tracking when the visitor clicks on the cancel button with exit intent):

_paq.push(["trackEvent", "Exit intent", "Click on button", "Cancel"]);
jstc.trackEvent("Exit intent", "Click on button", "Cancel");

Goal conversions

trackGoal(goalID[, conversionValue[, dimensions]])

Tracks manual goal conversion.

Arguments:
  • goalID (number|string) – Required Goal ID (integer or UUID)
  • conversionValue (number) – Optional Conversion value (revenue)
  • dimensions (object) – Optional Custom dimensions to pass along with the conversion

Example of usage (tracking conversion of goal 1 with value 15):

_paq.push(["trackGoal" 1, 15]);
jstc.trackGoal(1, 15);

E-commerce

addEcommerceItem(productSKU[, productName[, productCategory[, productPrice[, productQuantity]]]])

Adds a product to a virtual shopping cart. If a product with the same SKU is in the cart, it will be removed first. Does not send any data to the Collecting & Processing Pipeline.

Arguments:
  • productSKU (string) – Required Product stock-keeping unit
  • productName (string) – Optional Product name
  • productCategory (string|Array<string>) – Optional Product category or an array of up to 5 categories
  • productPrice (number) – Optional Product price
  • productQuantity (number) – Optional The number of units

Example of usage:

_paq.push(["addEcommerceItem", "craft-311", "Unicorn Iron on Patch", "Crafts & Sewing", 499, 3]);
jstc.addEcommerceItem("craft-311", "Unicorn Iron on Patch", "Crafts & Sewing", 499, 3);

Note

This function does not send any data to Collecting & Processing Pipeline. It only prepares the virtual shopping cart to be sent with trackEcommerceCartUpdate or trackEcommerceOrder.

Warning

The state of the virtual shopping cart is not persisted in browser storage. You must add all products again after a page reload.

Warning

Adding a product with a SKU that has been previously added will first remove the old product, e.g.:

_paq.push(["addEcommerceItem", "72625151", "Yellow notebook 150 pages", "School supplies", 10.00, 1]); // 1 item with sku 72625151
_paq.push(["addEcommerceItem", "72625151", "Yellow notebook 150 pages", "School supplies", 10.00, 2]); // 2 items with sku 72625151, not 3!
jstc.addEcommerceItem("72625151", "Yellow notebook 150 pages", "School supplies", 10.00, 1); // 1 item with sku 72625151
jstc.addEcommerceItem("72625151", "Yellow notebook 150 pages", "School supplies", 10.00, 2); // 2 items with sku 72625151, not 3!
removeEcommerceItem(productSKU)

Removes a product with the provided SKU from a virtual shopping cart. If multiple units of that product are in the virtual cart, all of them will be removed. Does not send any data to the Collecting & Processing Pipeline.

Arguments:
  • productSKU (string) – Required stock-keeping unit of a product to remove

Example of usage:

_paq.push(["removeEcommerceItem", "craft-311"]);
jstc.removeEcommerceItem("craft-311");

Note

This function does not send any data to Collecting & Processing Pipeline. It only prepares the virtual shopping cart to be sent with trackEcommerceCartUpdate or trackEcommerceOrder.

Warning

The state of the virtual shopping cart is not persisted in browser storage. You must add all products again after a page reload.

clearEcommerceCart()

Removes all items from a virtual shopping cart. Does not send any data to the Collecting & Processing Pipeline.

Example of usage:

_paq.push(["clearEcommerceCart"]);
jstc.clearEcommerceCart();

Note

This function does not send any data to Collecting & Processing Pipeline. It only prepares the virtual shopping cart to be sent with trackEcommerceCartUpdate or trackEcommerceOrder.

Warning

The state of the virtual shopping cart is not persisted in browser storage. You must add all products again after a page reload.

getEcommerceItems()

Returns a copy of items from a virtual shopping cart. Does not send any data to the Collecting & Processing Pipeline.

Returns:Object containing all tracked items (format: Object<productSKU, Array[productSKU, productName, productCategory, price, quantity]>)

Example of usage:

_paq.push([function () { console.log(this.getEcommerceItems()); }]);
console.log(jstc.getEcommerceItems());

Example return value:

{
    "52441051": ["52441051", "SUPER Notebook 15\" Ocean Blue", "Laptops", 2200, 1],
    "19287236": ["19287236", "Earbuds COOL PRO x300 BT", "Accessories", 85, 2],
}

Warning

The state of the virtual shopping cart is not persisted in browser storage. You must add all products again after a page reload.

setEcommerceView([productSKU[, productName[, productCategory[, productPrice]]]])

Tracks product or category view. Must be followed by a page view.

Arguments:
  • productSKU (string) – Optional Product stock-keeping unit.
  • productName (string) – Optional Product name.
  • productCategory (string|Array<string>) – Optional Category or an array of up to 5 categories.
  • productPrice (number) – Optional Category or an array of up to 5 categories.

When tracking product views, provide productSKU and optionally other parameters.

When tracking category views, provide only productCategory. Skip productSKU, productName and productPrice parameters supplying undefined where necessary.

Example of usage:

_paq.push(["setEcommerceView", undefined, undefined, "Crafts & Sewing"]); // category view
_paq.push(["trackPageView"]);

_paq.push(["setEcommerceView", "craft-311", "Unicorn Iron on Patch", "Crafts & Sewing", 499]); // product view
_paq.push(["trackPageView"]);
jstc.setEcommerceView(undefined, undefined, "Crafts & Sewing"); // category view
jstc.trackPageView();

jstc.setEcommerceView("craft-311", "Unicorn Iron on Patch", "Crafts & Sewing", 499); // product view
jstc.trackPageView();

Warning

setEcommerceView does not send data itself. It must be followed by a call to trackPageView.

trackEcommerceCartUpdate(cartAmount)

Tracks items present in a virtual shopping cart (registered with addEcommerceItem);

Arguments:
  • cartAmount (number) – Required The total value of items in the cart

Example of usage:

_paq.push(["trackEcommerceCartUpdate", 250]);
jstc.trackEcommerceCartUpdate(250);

Warning

Make sure all products from the cart have been registered using addEcommerceItem before tracking a cart update. Remember that when a page is reloaded, the cart resets and all products must be registered again.

trackEcommerceOrder(orderID, orderGrandTotal[, orderSubTotal[, orderTax[, orderShipping[, orderDiscount]]]])

Tracks a successfully placed e-commerce order with items present in a virtual cart (registered using addEcommerceItem).

Arguments:
  • orderID (string) – Required String uniquely identifying an order
  • orderGrandTotal (number) – Required Order Revenue grand total - tax, shipping and discount included
  • orderSubTotal (number) – Optional Order subtotal - without shipping
  • orderTax (number) – Optional Order tax amount
  • orderShipping (number) – Optional Order shipping cost
  • orderDiscount (number) – Optional Order discount amount

Example of usage:

_paq.push(["trackEcommerceOrder", "3352", 499, 399, 0, 100]);
jstc.trackEcommerceOrder("3352", 499, 399, 0, 100);

Warning

trackEcommerceOrder function clears the list with registered e-commerce items.

Custom Variables

Deprecated since version 5.5: We strongly advise using custom dimensions instead.

setCustomVariable(index, name[, value[, scope]])

Sets a custom variable that can be used later.

Arguments:
  • index (number) – Required Index from 1 to 5 where the variable is stored
  • name (string) – Required Name of the variable
  • value (string) – Optional Value of the variable, limited to 200 characters
  • scope (string) – Optional Scope of the variable, "visit" or "page". The default value is "visit".

Example of usage:

_paq.push(["setCustomVariable", 1, "AspectRatio", "16:9", "visit"]);
jstc.setCustomVariable(1, "AspectRatio", "16:9", "visit");

Note

A custom variable with the "visit" scope will be saved for an entire session, you don’t need to set it on every page.

Warning

Index is separate for each variable scope.

deleteCustomVariable(index[, scope])

Removes a previously set custom variable.

Arguments:
  • index (number) – Required Number from 1 to 5 where variable is stored
  • scope (string) – Optional Scope of the variable, "visit" or "page". The default value is "visit".

Example of usage:

_paq.push(["deleteCustomVariable", 1, "visit"]);
jstc.deleteCustomVariable(1, "visit");
getCustomVariable(index[, scope])

Returns the value of a previously set custom variable.

Arguments:
  • index (number) – Required Number from 1 to 5 where variable is stored
  • scope (string) – Optional Scope of the variable, "visit" or "page". The default value is "visit".
Return type:

Array[string, string]|boolean

Returns:

Custom variable value as an array with name and value if the custom variable exists or false if it doesn’t.

Example of usage:

_paq.push([function() {
    var customVariable = this.getCustomVariable(1, "visit");
    console.log(customVariable);
}]);
var customVariable = jstc.getCustomVariable(1, "visit");
console.log(customVariable);

Example return value:

["theme", "dark-01"]
storeCustomVariablesInCookie()

Enables storing "visit" type custom variables in a first party cookie.

Example of usage:

_paq.push(["storeCustomVariablesInCookie"]);
jstc.storeCustomVariablesInCookie();

Custom Dimensions

setCustomDimensionValue(customDimensionID, customDimensionValue)

New in version 15.3.

Sets a custom dimension to be used later.

Arguments:
  • customDimensionID (number) – Required ID of a custom dimension
  • customDimensionValue (string) – Required Value of a custom dimension

Example of usage:

_paq.push(["setCustomDimensionValue", 3, "loginStatus"]);
jstc.setCustomDimensionValue(3, "loginStatus");

Warning

When you set a custom dimension, its value will be used in all tracking requests within a page load.

Warning

This function does not send any data to the Collecting & Processing Pipeline. It prepares a custom dimension to be sent with following events, e.g. page view, e-commerce events, outlink or download events.

deleteCustomDimension(customDimensionID)

Removes a custom dimension with the specified ID.

Arguments:
  • customDimensionID (number) – Required ID of a custom dimension

Example of usage:

_paq.push(["deleteCustomDimension", 3]);
jstc.deleteCustomDimension(3);
getCustomDimensionValue(customDimensionID)

New in version 15.3.

Returns the value of a custom dimension with the specified ID.

Arguments:
  • customDimensionID (number) – Required ID of a custom dimension
Returns:

Value set with setCustomDimensionValue

Return type:

string

Example of usage:

_paq.push([function() {
    var customDimension = this.getCustomDimensionValue(3);
    console.log(customDimension);
}]);
var customDimension = this.getCustomDimensionValue(3);
setCustomDimension(customDimensionID, customDimensionValue)

Deprecated since version 15.3: Function setCustomDimension is deprecated due to the difficulty of use (passed values should be URL encoded). Please use setCustomDimensionValue instead.

Sets a custom dimension to be used later.

Arguments:
  • customDimensionID (number) – Required ID of a custom dimension
  • customDimensionValue (string) – Required Value of a custom dimension (should be URL encoded)

Example of usage:

_paq.push(["setCustomDimension", 3, "loginStatus"]);
jstc.setCustomDimension(3, "loginStatus");

Warning

When you set a Custom Dimension, that value will be used in all tracking requests within a page load.

Warning

This function does not send any data to the Collecting & Processing Pipeline. It sets a Custom Dimension to be sent with following events, e.g. page view, e-commerce events, outlink or download events.

getCustomDimension(customDimensionID)

Deprecated since version 15.3: Function getCustomDimension is deprecated due to the difficulty of use (returned values are URL-encoded). Please use getCustomDimensionValue instead.

Returns the value of a custom dimension.

Arguments:
  • customDimensionID (number) – Required ID of a custom dimension
Returns:

Value set with setCustomDimension

Return type:

string

Example of usage:

_paq.push([ function() {
    var customDimension = this.getCustomDimension(3);
    console.log(customDimension);
}]);
var customDimension = jstc.getCustomDimension(3);
console.log(customDimension);

Custom dimensions object

Some tracking functions accept an optional dimensions parameter. You can use it to pass additional custom dimensions along with the tracked event. Custom dimension object might look like this:

{
    "dimension1": "hello",
    "dimension4": "nice%20to%20see%20you",
    "dimension5": "goodbye"
}

Warning

Keys in a custom dimension object must be in "dimensionX" format, where X is the ID of a custom dimension. Keys that don’t match this format will be ignored.

Warning

Custom dimension values must be percent-encoded. To encode a string, pass it through encodeURIComponent function, e.g. encodeURIComponent("Äpfel?").

Content Tracking

Impressions

trackAllContentImpressions()

Scans the entire DOM for content blocks and tracks impressions after all page elements load. It does not send duplicates on repeated calls unless trackPageView was called in between trackAllContentImpressions invocations.

Example of usage:

_paq.push(["trackAllContentImpressions"]);
jstc.trackAllContentImpressions();
trackVisibleContentImpressions([checkOnScroll[, watchInterval]])

Scans DOM for all visible content blocks and tracks impressions.

Arguments:
  • checkOnScroll (boolean) – Optional Whether to scan for visible content on scroll event. Default value: true.
  • watchInterval (number) – Optional Delay, in milliseconds, between scans for new visible content. Periodic checks can be disabled by passing 0. Default value: 750.

Example of usage:

_paq.push(["trackVisibleContentImpressions", true, 2000]);
jstc.trackVisibleContentImpressions(true, 2000);

Warning

Neither option can be changed after the initial setup.

Warning

trackVisibleContentImpressions will not detect content blocks placed in a scrollable element.

trackContentImpressionsWithinNode(domNode)

Scans domNode (with its children) for all content blocks and tracks impressions.

Arguments:
  • domNode (Node) – Required DOM node with content blocks (elements with data-track-content attribute) inside

Example of usage:

var element = document.querySelector("#impressionContainer");
_paq.push(["trackContentImpressionsWithinNode", element]);
var element = document.querySelector("#impressionContainer");
jstc.trackContentImpressionsWithinNode(element);

Note

It can be used with trackVisibleContentImpressions to track only visible content impressions.

trackContentImpression(contentName, contentPiece, contentTarget)

Tracks manual content impression event.

Arguments:
  • contentName (string) – Required Name of a content block
  • contentPiece (string) – Required Name of the content that was displayed (e.g. link to an image)
  • contentTarget (string) – Required Where the content leads to (e.g. URL of some external website)

Example of usage:

_paq.push(["trackContentImpression", "promo-video", "https://example.com/public/promo-01.mp4", "https://example.com/more"]);
jstc.trackContentImpression("promo-video", "https://example.com/public/promo-01.mp4", "https://example.com/more");
logAllContentBlocksOnPage()

Print all content blocks to the console for debugging purposes.

Example output:

[
    {
        "name": "promo-video",
        "piece": "https://example.com/public/promo-01.mp4",
        "target": "https://example.com/more"
    }
]

Interactions

trackContentInteractionNode(domNode[, contentInteraction])

Tracks interaction with a block in domNode. Can be called from code placed in onclick attribute.

Arguments:
  • domNode (Node) – Required Node marked as content block or containing content blocks. If content block can’t be found, nothing will tracked.
  • contentInteraction (string) – Optional Name of interaction (e.g. "click"). Default value: "Unknown".

Example of usage:

var domNode = document.querySelector("#add-image");
_paq.push(["trackContentInteractionNode", domNode, "clicked"]);
var domNode = document.querySelector("#add-image");
jstc.trackContentInteractionNode(domNode, "clicked");

Example of usage in onclick attribute:

<button onclick="function(){_paq.push(['trackContentInteractionNode', this, 'clicked']);}">Click me!</button>
trackContentInteraction(contentInteraction, contentName, contentPiece, contentTarget)

Tracks manual content interaction event.

Arguments:
  • contentInteraction (string) – Required Type of interaction (e.g. "click")
  • contentName (string) – Required Name of a content block
  • contentPiece (string) – Required Name of the content that was displayed (e.g. link to an image)
  • contentTarget (string) – Required Where the content leads to (e.g. URL of some external website)

Example of usage:

_paq.push(["trackContentInteraction", "clicked", "trackingWhitepaper", "document", "http://cooltracker.tr/whitepaper"]);
jstc.trackContentInteraction("clicked", "trackingWhitepaper", "document", "http://cooltracker.tr/whitepaper");

Warning

Use this function in conjunction with trackContentImpression, as it can only be mapped with an impression by contentName.

User management

setUserId(userID)

Sets user ID, which will help identify a user of your application across many devices and browsers.

Arguments:
  • userID (string) – Required Non-empty, unique ID of a user in application

Example of usage:

_paq.push(["setUserId", "19283"]);
jstc.setUserId("19283");
resetUserId()

Clears previously set userID, e.g. when visitor logs out.

Example of usage:

_paq.push(["resetUserId"]);
jstc.resetUserId();
setUserIsAnonymous(isAnonymous)

Enables or disables anonymous tracking (anonymous = without consent). Does not send any data to Collecting & Processing Pipeline. The next emitted event will have anonymous mode set accordingly.

Arguments:
  • isAnonymous (boolean) – Required Whether visitor is anonymous

Example of usage:

_paq.push(["setUserIsAnonymous", true]);
jstc.setUserIsAnonymous(true);
deanonymizeUser()

Disables anonymous tracking and sends deanonymization event to the Collecting & Processing Pipeline. Recommended method for disabling anonymous tracking.

Example of usage:

_paq.push(["deanonymizeUser"]);
jstc.deanonymizeUser();
getVisitorId()

Returns 16-character hex ID of the visitor.

Example of usage:

_paq.push([function () {
    var visitorID = this.getVisitorId();
    console.log(visitorID);
}]);
var visitorID = jstc.getVisitorId();
console.log(visitorID);
getVisitorInfo()

Returns visitor information.

Return type:Array<string>
Returns:String array with the following visitor info:
  1. new visitor flag indicating new ("1") or returning ("0") visitor
  2. visitor ID (16-character hex number)
  3. first visit timestamp (UNIX epoch time)
  4. previous visit count ("0" for first visit)
  5. current visit timestamp (UNIX epoch time)
  6. last visit timestamp (UNIX epoch time or "" if N/A)
  7. last e-commerce order timestamp (UNIX epoch time or "" if N/A)

Example of usage:

_paq.push([function () {
    var info = this.getVisitorInfo();
    console.log(info);
}]);
var info = jstc.getVisitorInfo();
console.log(info);

Example output:

[
    "0",
    "6d85cb0b727eca52",
    "1624261490",
    "12",
    "1631115486",
    "1631115483",
    "1630590788"
]

Cross domain linking

enableCrossDomainLinking()

Enables cross domain linking. Visitors across domains configured with setDomains function will be linked by passing visitor ID parameter in links.

disableCrossDomainLinking()

Disables cross domain linking.

isCrossDomainLinkingEnabled()

Returns boolean telling whether cross domain linking is enabled.

setCrossDomainLinkingTimeout(seconds)

Changes the time in which two visits across domains will be linked. The default timeout is 180 seconds (3 minutes).

Arguments:
  • seconds (number) – Required Number of seconds in which two visits across domains will be linked
getCrossDomainLinkingUrlParameter()

Returns the name of a cross domain URL parameter (query parameter by default) holding visitor ID. This is "pk_vid" by default.

Example usage:

_paq.push([function () {
    var parameter = this.getCrossDomainLinkingUrlParameter();
}]);
var parameter = jstc.getCrossDomainLinkingUrlParameter();

Note

If your application creates links dynamically, you’ll have to add this parameter manually, e.g.

var url = "http://myotherdomain.com/path/?" + jstc.getCrossDomainLinkingUrlParameter();
$element.append('<a href="' + url + '">link</a>');
customCrossDomainLinkDecorator(urlDecorator)

Sets custom cross domains URL decorator for injecting visitor ID into URLs. Used when cross domain linking is enabled (see enableCrossDomainLinking()).

Arguments:
  • urlDecorator (function) – Required Function injecting a parameter to a URL address
urlDecorator(url, value, name)

Decorator function accepts link URL, parameter name, parameter value (visitor ID) and returns a URL containing the parameter data.

Arguments:
  • url (string) – Required Link URL
  • value (string) – Required Value of visitor ID that should be passed via URL
  • name (string) – Required Name of visitor ID parameter used by JavaScript Tracking Client (can be customized)
Returns:

Decorated URL or null (no change in URL)

Return type:

string|null

Example of usage (value sent via URL query parameter - equivalent of default implementation):

_paq.push(["customCrossDomainLinkDecorator", function (url, value, name) {
    var parsedUrl = new URL(url);
    parsedUrl.searchParams.append(name, value);
    return parsedUrl.href;
}]);
jstc.customCrossDomainLinkDecorator(function (url, value, name) {
    var parsedUrl = new URL(url);
    parsedUrl.searchParams.append(name, value);
    return parsedUrl.href;
}]);
customCrossDomainLinkVisitorIdGetter(urlParser)

Sets custom cross domain URL parser for extracting visitor ID from URLs. Should extract data injected by URL decorator (set via customCrossDomainLinkDecorator()). The getter should return visitor ID extracted from page URL (used by enableCrossDomainLinking()).

Arguments:
  • urlParser (function) – Required Function extracting a visitor ID from a URL address
urlParser(url, name)

Parser function accepts page URL, parameter name and returns parameter value (visitor ID).

Arguments:
  • url (string) – Required Page URL
  • name (string) – Required Name of parameter holding visitor ID
Returns:

Visitor ID value (parsed from URL)

Return type:

string

Example usage (value sent via URL query parameter - equivalent of default implementation):

_paq.push(["customCrossDomainLinkVisitorIdGetter", function (url, name) {
    return (new URL(url)).searchParams.get(name) || "";
}]);
jstc.customCrossDomainLinkVisitorIdGetter(function (url, name) {
    return (new URL(url)).searchParams.get(name) || "";
});

JavaScript Tracking Client configuration

setDomains(domains)

Allows to define a list of internal domains. Used in outlink tracking for determining whether a link is an outlink and in cross domain linking for determining which links should have visitor ID parameter injected.

Arguments:
  • domains (Array<string>) – Required A list of internal domains. Domains can contain wildcards: "*".

Example of usage:

_paq.push(["setDomains", ["*.example.com", "*.example.co.uk"]]);
jstc.setDomains(["*.example.com", "*.example.co.uk"]);
setDocumentTitle(title)

Overwrites document title internally. All events sent afterwards will use the provided document title. The title shown in a browser window is not affected.

Arguments:
  • title (string) – Required Custom title

Example of usage:

_paq.push(["setDocumentTitle", document.title.toLocaleLowerCase()]);
jstc.setDocumentTitle(document.title.toLocaleLowerCase());
setTimingDataSamplingOnPageLoad(sampling)

Configures page performance data collection. With non-zero sampling (5 by default), some page views will issue a page performance measurement.

Arguments:
  • sampling (number) – Required Page performance sampling, integer between 0 and 100. 0 disables page performance data collection. 100 measures every page load.

Example of usage:

_paq.push(["setTimingDataSamplingOnPageLoad", 0]); // disables page performance data collection
_paq.push(["setTimingDataSamplingOnPageLoad", 5]); // 5% of page views will by followed by a page performance measurement, this is the default behavior
_paq.push(["setTimingDataSamplingOnPageLoad", 30]); // 30% of page views will be followed by a page performance measurement
_paq.push(["setTimingDataSamplingOnPageLoad", 100]); // 100% of page views will be followed by a page performance measurement
jstc.setTimingDataSamplingOnPageLoad(0); // disables page performance data collection
jstc.setTimingDataSamplingOnPageLoad(5); // 5% of page views will by followed by a page performance measurement, this is the default behavior
jstc.setTimingDataSamplingOnPageLoad(30); // 30% of page views will be followed by a page performance measurement
jstc.setTimingDataSamplingOnPageLoad(100); // 100% of page views will be followed by a page performance measurement

Note

The default sampling value is 5, meaning 5% of page loads will be measured.

Warning

This setting will have an effect only if it’s used before the trackPageView.

Warning

If a page is closed before it fully loads (e.g. visitor closes the tab immediately after opening the page), page performance data will not be collected.

getTimingDataSamplingOnPageLoad()

Returns page performance sampling number.

Example of usage:

_paq.push([function () {
    console.log(this.getTimingDataSamplingOnPageLoad());
}]);
console.log(jstc.getTimingDataSamplingOnPageLoad());

Example output:

5
enableHeartBeatTimer()

When a visitor is not producing any events (e.g. because they are reading an article or watching a video), we don’t know if they are still on the page. This might skew page statistics, e.g. time on page value. Heartbeat timer allows us to determine how much time visitors spend on a page by sending heartbeats to the Collecting & Processing Pipeline as long as the page is in focus.

Example of usage:

_paq.push(["enableHeartBeatTimer"]);
jstc.enableHeartBeatTimer();

Note

The first heartbeat will be sent 15 seconds after the page load. The time between heartbeats increases with the number of heartbeats sent and stops at 5 minutes. When a page looses focus, heartbeats will be paused until the focus is restored. The last heartbeat is sent 30 minutes after the page view.

setLinkTrackingTimer(milliseconds)

When a visitor produces an events and closes the page immediately afterwards, e.g. when opening a link, the request might get cancelled. To avoid loosing the last event this way, JavaScript Tracking Client will lock the page for a fraction of a second (if wait time hasn’t passed), giving the request time to reach the Collecting & Processing Pipeline.

setLinkTrackingTimer allows to change the default lock/wait time of 500ms.

Arguments:

Example of usage:

_paq.push(["setLinkTrackingTimer", 100]);
jstc.setLinkTrackingTimer(100);

Note

Requests sent using beacon method do not lock the page.

Note

Contrary to what the function name suggests, setLinkTrackingTimer affects all other types of events. In recent versions of JavaScript Tracking Client, links are sent using beacon method if available.

getLinkTrackingTimer()

Returns lock/wait time after a request set by setLinkTrackingTimer.

Example of usage:

_paq.push([function () {
    var time = this.getLinkTrackingTimer();
    console.log(time);
}]);
var time = jstc.getLinkTrackingTimer();
console.log(time);
setSiteInspectorSetup(enable)

Site Inspector is a Chrome browser extension that helps visualize analytics data (e.g. click heat map, scroll map) on tracked pages. Default configuration of JavaScript Tracking Client will add configuration for this extension (in a page HTML), but it is possible to disable this behavior if you don’t need it.

Arguments:
  • enable (boolean) – Required Whether to enable site inspector support.

Example of usage:

_paq.push(["setSiteInspectorSetup", false]);
jstc.setSiteInspectorSetup(false);

Miscellaneous

ping()

Ping method sends requests that are not related to any visitor action, but can still update the session. the most common use for this method is updating session custom dimensions or custom variables.

Example of usage:

_paq.push(["ping"]);
jstc.ping();
addListener(domElement)

Adds automatic link tracking to an HTML element. Can be used to track links added to a document after page load.

Arguments:
  • domElement (DOMElement) – Required Element that should be tracked like a link.

Example of usage:

_paq.push(["addListener", document.querySelector("#dynamically-added-link")]);
jstc.addListener(document.querySelector("#dynamically-added-link"));
setRequestMethod(method)

Sets the request method. GET and POST are valid methods. GET is the default.

Arguments:
  • method (string) – Required Method that will be used in requests. Either "GET" or "POST".

Example of usage:

_paq.push(["setRequestMethod", "POST"]);
jstc.setRequestMethod("POST");
setRequestContentType(contentType)

Sets Content-Type header of tracking requests. Used when tracking using "POST" method (set by setRequestMethod).

Arguments:
  • contentType (string) – Required Content-Type value to be set.

Example of usage:

_paq.push(["setRequestContentType", "text/plain"]);
jstc.setRequestContentType("text/plain");
setCustomRequestProcessing(function)

Allows to access and modify query string before sending a page view or ping request.

Arguments:
  • function (function) – Required Function accepting a query string and returning another query string.

Example of usage:

_paq.push(["setCustomRequestProcessing", function (query) {
    var modifiedQuery = query.replace("rec=1", "rec=0");
    return modifiedQuery;
}]);
jstc.setCustomRequestProcessing(function (query) {
    var modifiedQuery = query.replace("rec=1", "rec=0");
    return modifiedQuery;
});
enableJSErrorTracking(unique)

Enables tracking of unhandled JavaScript errors.

Arguments:
  • unique (boolean) – Optional When set to true, tracker will send only unique errors from a page (duplicated errors will be ignored). Default: true.

Note

Browsers may limit information about error details if it occurs in script loaded from different origin (see details).

Example of usage:

_paq.push(["enableJSErrorTracking"]);
jstc.enableJSErrorTracking();
trackError(error)

Attempts to send error tracking request using same format as native errors caught by enableJSErrorTracking(). Such error request will still follow rules set for tracker, so it will be sent only when JS error tracking is enabled (enableJSErrorTracking() function was called before this attempt). It will also respect rules for tracking only unique errors.

Arguments:
  • error (Error) – Required Error object (e.g. caught with try...catch)

Example of usage:

_paq.push(["trackError", new Error("Uncaught SyntaxError")]);
jstc.trackError(new Error("Uncaught SyntaxError"));