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
Table of Contents
- API
- Command queue
- JavaScript Tracking Client object
- Tracking functions
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 instance
Return type: 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
Return type: object
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.setSiteId("45e07cbf-c8b3-42f3-a6d6-a5a176f623ef"); console.log(this.getSiteId()); }]);
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 Tracker. 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);
Site search¶
-
trackSiteSearch
(keyword[, category[, resultCount[, dimensions]]])¶ Tracks search requests on a website.
Arguments: - keyword (string) – Required What keyword the visitor entered into the search box
- category (string|Array<string>) – Optional Category selected in the search engine
- searchCount (number) – Optional The number of search results shown
- dimensions (object) – Optional Custom dimensions to pass along with the site search event
Example of usage:
_paq.push(["trackSiteSearch", "stove", undefined, 20]);
jstc.trackSiteSearch("stove", undefined, 20);
E-commerce v2¶
-
ecommerceProductDetailView
(products)¶ Tracks action of viewing product page.
Arguments: - products (Array<object>) –
Required List of product representations. Expected attributes of each product:
- sku - Required [string] Product stock-keeping unit
- name - Optional [string] Product name (default: “”)
- category - Optional [string|Array<string>] Product category or an array of up to 5 categories (default: “”)
- price - Optional [number|string] Product price has to be a float number or a string containing float number representation (default: 0)
- quantity - Optional [number|string] Product quantity has to be an integer number or a string containing integer representation (default: 1)
- brand - Optional [string] Product brand (default: “”)
- variant - Optional [string] Product variant (default: “”)
- customDimensions - Optional [object] Product custom dimensions (default: {})
Example of usage:
_paq.push([ "ecommerceProductDetailView", [{ sku: "craft-311", name: "Unicorn Iron on Patch", category: ["Crafts & Sewing", "Toys"], price: "49.90", quantity: 3, brand: "DMZ", variant: "blue", customDimensions: { 1: 'coupon-2020', 2: '20%' } }] ]);
jstc.ecommerceProductDetailView([{ sku: "craft-311", name: "Unicorn Iron on Patch", category: "Crafts & Sewing", price: "49.90", quantity: 3, brand: "DMZ", variant: "blue", customDimensions: { 1: 'coupon-2020', 2: '20%' } }]);
- products (Array<object>) –
-
ecommerceAddToCart
(products)¶ Tracks action of adding products to a cart.
Arguments: - products (Array<object>) –
Required List of product representations. Expected attributes of each product:
- sku - Required [string] Product stock-keeping unit
- name - Optional [string] Product name (default: “”)
- category - Optional [string|Array<string>] Product category or an array of up to 5 categories (default: “”)
- price - Optional [number|string] Product price has to be a float number or a string containing float number representation (default: 0)
- quantity - Optional [number|string] Product quantity has to be an integer number or a string containing integer representation (default: 1)
- brand - Optional [string] Product brand (default: “”)
- variant - Optional [string] Product variant (default: “”)
- customDimensions - Optional [object] Product custom dimensions (default: {})
Example of usage:
_paq.push([ "ecommerceAddToCart", [{ sku: "craft-311", name: "Unicorn Iron on Patch", category: "Crafts & Sewing", price: "49.90", quantity: 3, brand: "DMZ", variant: "blue", customDimensions: { 1: 'coupon-2020', 2: '20%' } }] ]);
jstc.ecommerceAddToCart([{ sku: "craft-311", name: "Unicorn Iron on Patch", category: "Crafts & Sewing", price: "49.90", quantity: 3, brand: "DMZ", variant: "blue", customDimensions: { 1: 'coupon-2020', 2: '20%' } }]);
- products (Array<object>) –
-
ecommerceRemoveFromCart
(products)¶ Tracks action of removing a product from a cart.
Arguments: - products (Array<object>) –
Required List of product representations. Expected attributes of each product:
- sku - Required [string] Product stock-keeping unit
- name - Optional [string] Product name (default: “”)
- category - Optional [string|Array<string>] Product category or an array of up to 5 categories (default: “”)
- price - Optional [number|string] Product price has to be a float number or a string containing float number representation (default: 0)
- quantity - Optional [number|string] Product quantity has to be an integer number or a string containing integer representation (default: 1)
- brand - Optional [string] Product brand (default: “”)
- variant - Optional [string] Product variant (default: “”)
- customDimensions - Optional [object] Product custom dimensions (default: {})
Example of usage:
_paq.push([ "ecommerceRemoveFromCart", [{ sku: "craft-311", name: "Unicorn Iron on Patch", category: "Crafts & Sewing", price: "49.90", quantity: 3, brand: "DMZ", variant: "blue", customDimensions: { 1: 'coupon-2020', 2: '20%' } }] ]);
jstc.ecommerceRemoveFromCart([{ sku: "craft-311", name: "Unicorn Iron on Patch", category: "Crafts & Sewing", price: "49.90", quantity: 3, brand: "DMZ", variant: "blue", customDimensions: { 1: 'coupon-2020', 2: '20%' } }]);
- products (Array<object>) –
-
ecommerceCartUpdate
(products, grandTotal)¶ Tracks current state of a cart.
Arguments: - products (Array<object>) –
Required List of product representations. Expected attributes of each product:
- sku - Required [string] Product stock-keeping unit
- name - Optional [string] Product name (default: “”)
- category - Optional [string|Array<string>] Product category or an array of up to 5 categories (default: “”)
- price - Optional [number|string] Product price has to be a float number or a string containing float number representation (default: 0)
- quantity - Optional [number|string] Product quantity has to be an integer number or a string containing integer representation (default: 1)
- brand - Optional [string] Product brand (default: “”)
- variant - Optional [string] Product variant (default: “”)
- customDimensions - Optional [object] Product custom dimensions (default: {})
- grandTotal (number) – Required [number|string] The total value of items in a cart has to be a float number or a string containing float number representation
Example of usage:
_paq.push([ "ecommerceCartUpdate", [ { sku: "craft-311", name: "Unicorn Iron on Patch", category: "Crafts & Sewing", price: "150.00", quantity: 3, brand: "DMZ", variant: "blue", customDimensions: { 1: 'coupon-2020', 2: '20%' } }, { sku: "craft-312", name: "Unicorn Iron on Grass", category: "Crafts & Sewing", price: "30.00", quantity: 1, brand: "DMZ", variant: "red", customDimensions: { 1: 'coupon-2020', 2: '20%' } } ], "180.00" ]);
jstc.ecommerceCartUpdate( [ { sku: "craft-311", name: "Unicorn Iron on Patch", category: "Crafts & Sewing", price: "150.00", quantity: 3, brand: "DMZ", variant: "blue", customDimensions: { 1: 'coupon-2020', 2: '20%' } }, { sku: "craft-312", name: "Unicorn Iron on Grass", category: "Crafts & Sewing", price: "30.00", quantity: 1, brand: "DMZ", variant: "red", customDimensions: { 1: 'coupon-2020', 2: '20%' } } ], "180.00" );
- products (Array<object>) –
-
ecommerceOrder
(products, paymentInformation)¶ Tracks conversion (including products and payment details).
Arguments: - products (Array<object>) –
Required List of product representations. Expected attributes of each product:
- sku - Required [string] Product stock-keeping unit
- name - Optional [string] Product name (default: “”)
- category - Optional [string|Array<string>] Product category or an array of up to 5 categories (default: “”)
- price - Optional [number|string] Product price has to be a float number or a string containing float number representation (default: 0)
- quantity - Optional [number|string] Product quantity has to be an integer number or a string containing integer representation (default: 1)
- brand - Optional [string] Product brand (default: “”)
- variant - Optional [string] Product variant (default: “”)
- customDimensions - Optional [object] Product custom dimensions (default: {})
- paymentInformation (object) –
Total payment information about products in a cart. Expected attributes:
- orderId - Required [string] Unique identifier of an order
- grandTotal - Required [number|string] The total value of items in a cart has to be a float number or a string containing float number representation
- subTotal - Optional [number|string] Total value of items in a cart without shipping has to be a float number or a string containing float number representation
- tax - Optional [number|string] Total tax amount has to be a float number or a string containing float number representation
- shipping - Optional [number|string] Total shipping cost has to be a float number or a string containing float number representation
- discount - Optional [number|string] Total discount has to be a float number or a string containing float number representation
Example of usage:
_paq.push([ "ecommerceOrder", [ { sku: "craft-311", name: "Unicorn Iron on Patch", category: "Crafts & Sewing", price: "150.00", quantity: 3, brand: "DMZ", variant: "blue", customDimensions: { 1: 'coupon-2020', 2: '20%' } }, { sku: "craft-312", name: "Unicorn Iron on Grass", category: "Crafts & Sewing", price: "30.00", quantity: 1, brand: "DMZ", variant: "red", customDimensions: { 1: 'coupon-2020', 2: '20%' } } ], { orderId: "order-3415", grandTotal: "180.00", subTotal: "120.00", tax: "39.60", shipping: "60.00", discount: "18.00" } ]);
jstc.ecommerceOrder( [ { sku: "craft-311", name: "Unicorn Iron on Patch", category: "Crafts & Sewing", price: "150.00", quantity: 3, brand: "DMZ", variant: "blue", customDimensions: { 1: 'coupon-2020', 2: '20%' } }, { sku: "craft-312", name: "Unicorn Iron on Grass", category: "Crafts & Sewing", price: "30.00", quantity: 1, brand: "DMZ", variant: "red", customDimensions: { 1: 'coupon-2020', 2: '20%' } } ], { orderId: "order-3415", grandTotal: "180.00", subTotal: "120.00", tax: "39.60", shipping: "60.00", discount: "18.00" } );
- products (Array<object>) –
E-commerce¶
Deprecated since version TBA: Older ecommerce API deprecated in favor of e-commerce V2. New API allows to track more actions (e.g. ecommerceAddToCart) and is easier to use.
-
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 Tracker.
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 Tracker. 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 Tracker.
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 Tracker. 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 Tracker.
Example of usage:
_paq.push(["clearEcommerceCart"]);
jstc.clearEcommerceCart();
Note
This function does not send any data to Tracker. 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 Tracker.
Returns: Object containing all tracked items (format: Object<productSKU, Array[productSKU, productName, productCategory, price, quantity]>
)Return type: object 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 Product price.
When tracking product views, provide
productSKU
and optionally other parameters.When tracking category views, provide only
productCategory
. SkipproductSKU
,productName
andproductPrice
parameters supplyingundefined
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"
.
Returns: Custom variable value as an array with name and value if the custom variable exists (e.g.
["theme", "dark-01"]
) orfalse
if it doesn’t.Return type: string[]|boolean
Example of usage:
_paq.push([function() { console.log(this.getCustomVariable(1, "visit")); }]);
console.log(jstc.getCustomVariable(1, "visit"));
-
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 Tracker. 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 (e.g.
"loginStatus"
)Return type: string
Example of usage:
_paq.push([function() { console.log(this.getCustomDimensionValue(3)); }]);
console.log(jstc.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 Tracker. 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 (e.g.
"loginStatus"
)Return type: string
Example of usage:
_paq.push([ function() { console.log(this.getCustomDimension(3)); }]);
console.log(jstc.getCustomDimension(3));
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 betweentrackAllContentImpressions
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.- checkOnScroll (boolean) – Optional Whether to scan for visible content on
-
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.- domNode (Node) – Required DOM node with content blocks (elements with
-
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 of usage:
_paq.push(["logAllContentBlocksOnPage"]);
jstc.logAllContentBlocksOnPage();
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 bycontentName
.- contentInteraction (string) – Required Type of interaction (e.g.
Download and Outlink¶
-
trackLink
(linkAddress, linkType[, dimensions[, callback]])¶ Manually tracks outlink or download event with provided values.
Arguments: - linkAddress (string) – Required URL address of the link
- linkType (string) – Required Type of the link,
"link"
for outlink,"download"
for download - dimensions (object) – Optional Custom dimensions to pass along with the link event
- callback (function) – Optional Function that should be called after tracking the link
Example of usage:
_paq.push(["trackLink", "http://www.example.com/example", "link"]);
jstc.trackLink("http://www.example.com/example", "link");
Example of usage in
onclick
attribute:<button onclick="_paq.push(['trackLink', 'http://www.example.com/example', 'link'])"> Click me! </button>
-
enableLinkTracking
([trackMiddleAndRightClicks])¶ Enables automatic link tracking. By default, left, right and middle clicks on links will be treated as opening a link. Opening a link to an external site (different domain) creates an outlink event. Opening a link to a downloadable file creates a download event.
Arguments: - trackMiddleAndRightClicks (boolean) – Optional Whether to treat middle and right clicks as opening a link. The default value is
true
.
Example of usage:
_paq.push(["trackPageView"]); _paq.push(["enableLinkTracking"]);
jstc.trackPageView(); jstc.enableLinkTracking();
Note
enableLinkTracking
is a part of the default Tag Manager’s tracking code snippet. It’s likely your setup already has it.Note
Outlink events are tracked only when a link points to a different (external) domain. If that domain belongs to you and you don’t want to track outlinks when visitors open it, use setDomains function to define internal domains and subdomains.
Warning
enableLinkTracking
should be called right after the firsttrackPageView
ortrackEvent
.- trackMiddleAndRightClicks (boolean) – Optional Whether to treat middle and right clicks as opening a link. The default value is
-
disableLinkTracking
()¶ Disables automatic link tracking (if it was enabled previously with
enableLinkTracking()
).Example of usage:
_paq.push(["disableLinkTracking"]);
jstc.disableLinkTracking();
-
setIgnoreClasses
(classes)¶ Set a list of class names that indicate a link should not be tracked.
Arguments: - classes (string|Array<string>) – Required CSS class name or an array of class names
Example of usage:
_paq.push(["setIgnoreClasses", ["do-not-track", "ignore-link"]]);
jstc.setIgnoreClasses(["do-not-track", "ignore-link"]);
Note
Elements with
piwik-ignore
andpiwik_ignore
classes are always ignored.
-
setLinkClasses
(classes)¶ Sets a list of class names that indicate whether a link is an outlink and not download.
Arguments: - classes (string|Array<string>) – Required CSS class name or an array of class names
Example of usage:
_paq.push(["setLinkClasses", "this-is-an-outlink"]);
jstc.setLinkClasses("this-is-an-outlink");
Note
Elements with
piwik-link
orpiwik_link
class are always treated as outlinks.
-
setDownloadClasses
(classes)¶ Sets a list of class names that indicate whether a list is a download and not an outlink.
Arguments: - classes (string|Array<string>) – Required CSS class name or an array of class names
Example of usage:
_paq.push(["setDownloadClasses", "this-is-a-download"]);
jstc.setDownloadClasses("this-is-a-download");
Note
Elements with
download
attribute,piwik-download
class orpiwik_download
class are always treated as downloads.Note
Links containing a known file extension will be treated as a downloads as well.
-
setDownloadExtensions
(extensions)¶ Overwrites the list of file extensions indicating that a link is a download.
Arguments: - extensions (string|Array<string>) – Required List of extensions to
be set. Can be written as string, e.g.
"zip|rar"
, or an array, e.g.["zip", "rar"]
.
Links containing a known file extension are treated as downloads and not outlinks. We check for extensions at the end of URL path and in query parameter values. Below are examples of URL with extensions detected.
- http://example.com/path/file.zip
- http://example.com/path/file.zip#hello
- http://example.com/path/file.zip?a=102
- http://example.com/path/?a=file.zip
- http://example.com/path/?a=file.zip&b=29
The default download extensions list contains the following extensions:
7z
,aac
,apk
,arc
,arj
,asf
,asx
,avi
,azw3
,bin
,csv
,deb
,dmg
,doc
,docx
,epub
,exe
,flv
,gif
,gz
,gzip
,hqx
,ibooks
,jar
,jpg
,jpeg
,js
,mobi
,mp2
,mp3
,mp4
,mpg
,mpeg
,mov
,movie
,msi
,msp
,odb
,odf
,odg
,ods
,odt
,ogg
,ogv
,pdf
,phps
,png
,ppt
,pptx
,qt
,qtm
,ra
,ram
,rar
,rpm
,sea
,sit
,tar
,tbz
,tbz2
,bz
,bz2
,tgz
,torrent
,txt
,wav
,wma
,wmv
,wpd
,xls
,xlsx
,xml
,z
,zip
Example of usage:
_paq.push(["setDownloadExtensions", "mhj|docx"]);
jstc.setDownloadExtensions("mhj|docx");
Warning
The list of download extensions is not persisted in the browser. It has to be configured on every page load.
- extensions (string|Array<string>) – Required List of extensions to
be set. Can be written as string, e.g.
-
addDownloadExtensions
(extensions)¶ Adds new extensions to the download extensions list.
Arguments: - extensions (string|Array<string>) – Required List of extensions to
be added. Can be written as string, e.g.
"7z|apk|mp4"
, or an array, e.g.["7z","apk","mp4"]
.
Warning
The list of download extensions is not persisted in the browser. It has to be configured on every page load.
Example of usage:
_paq.push(["addDownloadExtensions", "mhj|docx"]);
jstc.addDownloadExtensions("mhj|docx");
- extensions (string|Array<string>) – Required List of extensions to
be added. Can be written as string, e.g.
-
removeDownloadExtensions
(extensions)¶ Removes extensions from the download extensions list.
Arguments: - extensions (string|Array<string>) – Required List of extensions to
remove. Can be written as string, e.g.
"zip|rar"
, or an array, e.g.["zip", "rar"]
.
Example of usage:
_paq.push(["removeDownloadExtensions", "mhj|docx"]);
jstc.removeDownloadExtensions("mhj|docx");
Warning
The list of download extensions is not persisted in the browser. It has to be configured on every page load.
- extensions (string|Array<string>) – Required List of extensions to
remove. Can be written as string, e.g.
-
getConfigDownloadExtensions
()¶ Returns current download extensions list used by the JSTC.
Returns: List of download extensions (e.g.``[“mhj”, “docx”]``). Return type: string[] Example of usage:
_paq.push([function () { console.log(this.getConfigDownloadExtensions()); }]);
console.log(jstc.getConfigDownloadExtensions());
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");
-
getUserId
()¶ Returns currently used user ID value (set with
setUserId()
).Returns: User ID value (e.g. "19283"
)Return type: string Example of usage:
_paq.push([function () { console.log(this.getUserId()); }]);
console.log(jstc.getUserId());
-
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). The next emitted event will have anonymous mode set accordingly.
Arguments: - isAnonymous (boolean) – Required Whether visitor is anonymous
true
- all IP bytes will be masked (0.0.0.0), GeoIP data below Country level will be anonymizedfalse
- available visitor data will be added to the session
Example of usage:
_paq.push(["setUserIsAnonymous", true]);
jstc.setUserIsAnonymous(true);
-
deanonymizeUser
()¶ Disables anonymous tracking and sends deanonymization event to the Tracker. Recommended method for disabling anonymous tracking.
Example of usage:
_paq.push(["deanonymizeUser"]);
jstc.deanonymizeUser();
-
setSessionIdStrictPrivacyMode
(isStrict)¶ Enables or disables strict privacy option in the tracker. When enabled tracker will not send information that can be used to fully or partially identify individual client browser even when persistent cookies are disabled. The information about browser that is blocked by this setting: screen resolution and installed browser plugins (e.g. PDF, Flash, Silverlight, Java, QuickTime, RealAudio, etc.).
Arguments: - isStrict (boolean) – Required Defines if tracker should use strict privacy mode.
Example of usage:
_paq.push(["setSessionIdStrictPrivacyMode", true]);
jstc.setSessionIdStrictPrivacyMode(true);
-
setIpTracking
(status)¶ Enables or disables recording of IP option in the tracker. When disabled backend tracker will not record IP information attached to following requests.
Arguments: - status (boolean) – Required Defines if backend tracker will record IP information attached to following requests. Values:
true
- record IP data,false
- ignore IP data (default value istrue
).
Example of usage:
_paq.push(["setIpTracking", false]);
jstc.setIpTracking(false);
- status (boolean) – Required Defines if backend tracker will record IP information attached to following requests. Values:
-
getVisitorId
()¶ Returns 16-character hex ID of the visitor.
Returns: Visitor ID (e.g. "0123456789abcdef"
Return type: string Example of usage:
_paq.push([function () { console.log(this.getVisitorId()); }]);
console.log(jstc.getVisitorId());
-
getVisitorInfo
()¶ Returns visitor information.
Return type: string[] Returns: String array with the following visitor info: - new visitor flag indicating new (
"1"
) or returning ("0"
) visitor - visitor ID (16-character hex number)
- first visit timestamp (UNIX epoch time)
- previous visit count (
"0"
for first visit) - current visit timestamp (UNIX epoch time)
- last visit timestamp (UNIX epoch time or
""
if N/A) - last e-commerce order timestamp (UNIX epoch time or
""
if N/A)
Example of usage:
_paq.push([function () { console.log(this.getVisitorInfo()); }]);
console.log(jstc.getVisitorInfo());
Example output:
[ "0", "6d85cb0b727eca52", "1624261490", "12", "1631115486", "1631115483", "1630590788" ]
- new visitor flag indicating new (
Cookie management¶
-
enableCookies
()¶ Enables all first party cookies. Cookies will be created on the next tracking request.
Example of usage:
_paq.push(["enableCookies"]);
jstc.enableCookies();
Note
JavaScript Tracking Client has cookies enabled by default.
-
disableCookies
()¶ Disables all first party cookies. Existing cookies will be deleted in the next page view.
Example of usage:
_paq.push(["disableCookies"]);
jstc.disableCookies();
-
deleteCookies
()¶ Deletes existing tracking cookies on the next page view.
Example of usage:
_paq.push(["deleteCookies"]);
jstc.deleteCookies();
-
hasCookies
()¶ Returns
true
if cookies are enabled in this browser.Returns: Status of cookies support by the browser (e.g. true
)Return type: boolean Example of usage:
_paq.push([function () { console.log(this.hasCookies()); }]);
console.log(jstc.hasCookies());
-
setCookieNamePrefix
(prefix)¶ Sets the prefix for analytics tracking cookies. Default is
"_pk_"
.Arguments: - prefix (string) – Required String that will replace default analytics tracking cookies prefix.
Example of usage:
_paq.push(["setCookieNamePrefix", "_examplePrefix_"]);
jstc.setCookieNamePrefix("_examplePrefix_");
-
setCookieDomain
(domain)¶ Sets the domain for the analytics tracking cookies.
Arguments: - domain (string) – Required Domain that will be set as cookie domain. For enabling subdomain you can use wildcard sign or dot.
Example of usage:
_paq.push(["setCookieDomain", ".example.com"]);
jstc.setCookieDomain(".example.com");
-
getCookieDomain
()¶ Returns domain of the analytics tracking cookies (set with
setCookieDomain()
).Returns: Domain of the analytics tracking cookies (e.g. ".example.com"
)Return type: string Example of usage:
_paq.push([function () { console.log(this.getCookieDomain()); }]);
console.log(jstc.getCookieDomain());
-
setCookiePath
(path)¶ Sets the analytics tracking cookies path.
Arguments: - path (string) – Required Path that will be set, default is
"/"
.
Example of usage:
_paq.push(["setCookiePath", "/blog/"]);
jstc.setCookiePath("/blog/");
- path (string) – Required Path that will be set, default is
-
getCookiePath
()¶ Returns the analytics tracking cookies path.
Returns: Analytics tracking cookies path (e.g. "/blog/"
).Return type: string Example of usage:
_paq.push([function () { console.log(this.getCookiePath()); }]);
console.log(jstc.getCookiePath());
-
setSecureCookie
(secure)¶ Toggles the secure cookie flag on all first party cookies (if you are using HTTPS).
Arguments: - secure (boolean) – Required Whether to add secure flag to cookies.
Example of usage:
_paq.push(["setSecureCookie", true]);
jstc.setSecureCookie(true);
-
setVisitorCookieTimeout
(seconds)¶ Sets the expiration time of visitor cookies.
Arguments: - seconds (number) – Required Number of seconds after which the cookie will expire. Default is 13 months.
Example of usage:
_paq.push(["setVisitorCookieTimeout", 33955200]);
jstc.setVisitorCookieTimeout(33955200);
-
getConfigVisitorCookieTimeout
()¶ Returns expiration time of visitor cookies (in milliseconds).
Returns: Expiration time of visitor cookies in milliseconds (e.g. 33955200000
)Return type: number Example of usage:
_paq.push([function () { console.log(this.getConfigVisitorCookieTimeout()); }]);
console.log(jstc.getConfigVisitorCookieTimeout());
-
setReferralCookieTimeout
(seconds)¶ Sets the expiration time of referral cookies.
Arguments: - seconds (number) – Required Number of seconds after which the cookie will expire. Default is 6 months.
Example of usage:
_paq.push(["setReferralCookieTimeout", 15768000]);
jstc.setReferralCookieTimeout(15768000);
-
setSessionCookieTimeout
(seconds)¶ Sets the expiration time of session cookies.
Arguments: - seconds (number) – Required Number of seconds after which the cookie will expire. Default is 30 minutes.
Example of usage:
_paq.push(["setSessionCookieTimeout", 1800000]);
jstc.setSessionCookieTimeout(1800000);
-
getSessionCookieTimeout
()¶ Returns expiration time of session cookies.
Returns: Expiration time of session cookies Return type: number Example of usage:
_paq.push([function () { console.log(this.getSessionCookieTimeout()); }]);
console.log(jstc.getSessionCookieTimeout());
-
setVisitorIdCookie
()¶ Sets cookie containing analytics ID in browser.
Example of usage:
_paq.push(["setVisitorIdCookie"]);
jstc.setVisitorIdCookie();
Note
It’s needed only when JavaScript Tracking Client instance is created without use of
_paq.push()
and script needs to know analytics ID before first tracking request is sent. Make sure that it is called after all methods that configure cookie are called (e.g.setCookieNamePrefix()
,setCookieDomain()
,setCookiePath()
, etc.).
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.
Example of usage:
_paq.push(["enableCrossDomainLinking"]);
jstc.enableCrossDomainLinking();
-
disableCrossDomainLinking
()¶ Disables cross domain linking.
Example of usage:
_paq.push(["disableCrossDomainLinking"]);
jstc.disableCrossDomainLinking();
-
isCrossDomainLinkingEnabled
()¶ Returns boolean telling whether cross domain linking is enabled.
Returns: Status of cross domain linking (e.g. true
)Return type: boolean Example of usage:
_paq.push([function () { console.log(this.isCrossDomainLinkingEnabled()); }]);
console.log(jstc.isCrossDomainLinkingEnabled());
-
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
Example of usage:
_paq.push(["setCrossDomainLinkingTimeout", 180]);
jstc.setCrossDomainLinkingTimeout(180);
-
getCrossDomainLinkingUrlParameter
()¶ Returns the name of a cross domain URL parameter (query parameter by default) holding visitor ID. This is
"pk_vid"
by default.Returns: Name of a cross domain URL parameter (e.g. "pk_vid"
)Return type: string Example usage:
_paq.push([function () { console.log(this.getCrossDomainLinkingUrlParameter()); }]);
console.log(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 byenableCrossDomainLinking()
).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¶
-
addTracker
(trackerUrl, siteId)¶ Creates new 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
Return type: object
Example of usage:
_paq.push(["addTracker", "https://example.piwik.pro/piwik.php", "45e07cbf-c8b3-42f3-a6d6-a5a176f623ef"]);
jstc.addTracker("https://example.piwik.pro/piwik.php", "45e07cbf-c8b3-42f3-a6d6-a5a176f623ef");
-
setTrackerUrl
(url)¶ Overrides Piwik tracking URL set at the JSTC initiation.
Arguments: - url (string) – Required Path to Piwik tracking URL (e.g.
"https://example.piwik.pro/piwik.php"
)
Example of usage:
_paq.push(["setTrackerUrl", "https://example.piwik.pro/piwik.php"]);
jstc.setTrackerUrl("https://example.piwik.pro/piwik.php");
- url (string) – Required Path to Piwik tracking URL (e.g.
-
getTrackerUrl
()¶ Returns the Piwik tracking URL used by tracker (either default, set during tracker initiation or override value set with
setTrackerUrl()
).Returns: Piwik tracking URL (e.g. "https://example.piwik.pro/piwik.php"
)Return type: string Example of usage:
_paq.push([function () { console.log(this.getTrackerUrl()); }]);
console.log(jstc.getTrackerUrl());
Returns: Currently used Piwik tracking URL (e.g. "https://example.piwik.pro/"
)Return type: string
-
setAPIUrl
(url)¶ Overrides HTTP API URL for tracking endpoint that was set at the tracker initiation. The use of this function is discouraged, as JavaScript Tracking Client should select the correct URL.
Deprecated since version 16.17: This method is outdated, use
setTrackerUrl()
instead.Arguments: - url (string) – Required Path to HTTP API URL (e.g. “https://example.piwik.pro”)
Example of usage:
_paq.push(["setAPIUrl", "https://example.piwik.pro/piwik.php"]);
jstc.setAPIUrl("https://example.piwik.pro/piwik.php");
-
getPiwikUrl
()¶ Returns the HTTP API URL used by tracker (either default, set during tracker initiation or override value set with
setAPIUrl()
).Returns: Currently used HTTP API URL (e.g. "https://example.piwik.pro/piwik.php"
)Return type: string Deprecated since version 16.17: This method is outdated, use
getTrackerUrl()
instead.Example of usage:
_paq.push([function () { console.log(this.getPiwikUrl()); }]);
console.log(jstc.getPiwikUrl());
-
setSiteId
(siteId)¶ Sets site ID that wil be linked to tracked data.
Arguments: - siteId (string) – Required Site ID that will be linked to tracked data.
Example of usage:
_paq.push(["setSiteId", "45e07cbf-c8b3-42f3-a6d6-a5a176f623ef"]);
jstc.setSiteId("45e07cbf-c8b3-42f3-a6d6-a5a176f623ef");
-
getSiteId
()¶ Returns site ID linked to tracked data.
Returns: Site ID linked to tracked data (e.g. "45e07cbf-c8b3-42f3-a6d6-a5a176f623ef"
)Return type: string Example of usage:
_paq.push([function () { console.log(this.getSiteId()); }]);
console.log(jstc.getSiteId());
-
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 wildcard character (
"*"
) or leading dot.
Example of usage:
_paq.push(["setDomains", [".example.com", ".example.co.uk"]]);
jstc.setDomains([".example.com", ".example.co.uk"]);
- domains (Array<string>) – Required A list of internal domains. Domains can contain wildcard character (
-
getDomains
()¶ Returns list of internal domains (set with
setDomains()
and used in outlink tracking).Returns: List of internal domains (e.g. [".example.com", ".example.co.uk"]
Return type: string[] Example of usage:
_paq.push([function () { console.log(this.getDomains()); }]);
console.log(jstc.getDomains());
-
setCustomUrl
(customUrl)¶ The function that will override tracked page URL. Tracker will use current page URL if custom URL was not set.
Arguments: - customUrl (string) – Required Value that will override default URL of the tracked page.
Example of usage:
_paq.push(["setCustomUrl", "https://example.com/virtual-page"]);
jstc.setCustomUrl("https://example.com/virtual-page");
-
getCurrentUrl
()¶ Returns the current URL of the page. The custom URL will be returned if set with
setCustomUrl()
.Returns: Currently tracked page URL (e.g. "https://example.com/virtual-page"
)Return type: string Example of usage:
_paq.push([function () { console.log(this.getCurrentUrl()); }]);
console.log(jstc.getCurrentUrl());
-
setReferrerUrl
(url)¶ The function that will override the detected HTTP referrer.
Arguments: - url (string) – Required Value that will override HTTP referrer.
Example of usage:
_paq.push(["setReferrerUrl", "https://example.com/previous-page"]);
jstc.setReferrerUrl("https://example.com/previous-page");
-
discardHashTag
(enableFilter)¶ When enabled, JSTC will remove URL fragment identifier from all tracked URLs (e.g. current page URL, referer URL, etc.).
Arguments: - enableFilter (boolean) – Required If set to true, URL fragment identifier will be removed from tracked URLs.
Example of usage:
_paq.push(["discardHashTag", true]);
jstc.discardHashTag(true);
-
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 (10 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", 10]); // 10% 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(10); // 10% 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 10, meaning 10% 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.
-
disablePerformanceTracking
()¶ Disables sending page performance metrics for page views. Page performance metrics are enabled by default, but on SPA pages they are correct only for the first page view. All following page views in SPA don’t reload whole page so in such cases it’s better to disable page performance tracking to avoid reporting invalid loading times for such pages.
Example of usage:
_paq.push(["disablePerformanceTracking"]);
jstc.disablePerformanceTracking();
-
getTimingDataSamplingOnPageLoad
()¶ Returns page performance sampling number.
Returns: Percentage of page performance sampling (e.g. 10
)Return type: number Example of usage:
_paq.push([function () { console.log(this.getTimingDataSamplingOnPageLoad()); }]);
console.log(jstc.getTimingDataSamplingOnPageLoad());
-
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 Tracker 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.
-
disableHeartBeatTimer
()¶ Disables sending heartbeats if they were previously enabled by
enableHeartBeatTimer()
.Example of usage:
_paq.push(["disableHeartBeatTimer"]);
jstc.disableHeartBeatTimer();
-
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 Tracker.
setLinkTrackingTimer
allows to change the default lock/wait time of 500ms.Arguments: - milliseconds (number) – Required How many milliseconds a request needs to reach the Tracker.
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 usingbeacon
method if available.
-
getLinkTrackingTimer
()¶ Returns page exit delay (in milliseconds). Default delay can be changed with setLinkTrackingTimer.
Returns: Page exit delay (e.g. 500
)Return type: number Example of usage:
_paq.push([function () { console.log(this.getLinkTrackingTimer()); }]);
console.log(jstc.getLinkTrackingTimer());
-
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
andPOST
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");
- method (string) – Required Method that will be used in requests. Either
-
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 tracking request.
You may even prevent the tracking request from being sent at all by clearing out the query parameter (returning an empty string).
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();
- unique (boolean) – Optional When set to true, tracker will send only unique errors from a page (duplicated errors will be ignored). Default:
-
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"));
- error (Error) – Required Error object (e.g. caught with
-
getTrackingSource
()¶ Returns tracking source name and version that identifies the library sending tracking requests. The default tracking source is
jstc
and can be overwritten using setTrackingSource function.Returns: An array with tracking source name and version, e.g. ["jstc", "2.3.1"]
Return type: string[] Example of usage:
_paq.push([function() { var nameAndVersion = this.getTrackingSource(); console.log("name: " + nameAndVersion[0]); console.log("version: " + nameAndVersion[1]); }]);
var nameAndVersion = jstc.getTrackingSource(); console.log("name: " + nameAndVersion[0]); console.log("version: " + nameAndVersion[1]);
-
setTrackingSource
(name, version)¶ Overwrites the default tracking source.
Arguments: - name (string) – Required Tracking source name, e.g.
"custom-source"
- version (string) – Optional Tracking source version in Semantic Versioning format, e.g.
"1.0.0"
. If skipped, the version will not change.
Example of usage:
_paq.push(["setTrackingSource", "custom-source", "1.0.0"]);
jstc.setTrackingSource("custom-source", "1.0.0");
- name (string) – Required Tracking source name, e.g.
-
setGenerationTimeMs
(generationTime)¶ Overrides reported time needed to download current page (by default this value is fetched from DOM Timing API).
Deprecated since version 16.17: Server generation time is phased out in favor of page performance metrics.
Arguments: - generationTime (number) – Required Time that server took to generate current page (in milliseconds).
Example of usage:
_paq.push(["setGenerationTimeMs", 2546]);
jstc.setGenerationTimeMs(2546);
-
appendToTrackingUrl
(appendToUrl)¶ Appends provided query string to each tracking request.
Arguments: - appendToUrl (string) – Required Custom query string that will be attached to each tracking request (e.g.
"lat=140&long=100"
). Parameter names and values should be already URL encoded.
Example of usage:
_paq.push(["appendToTrackingUrl", "lat=140&long=100"]);
jstc.appendToTrackingUrl("lat=140&long=100");
- appendToUrl (string) – Required Custom query string that will be attached to each tracking request (e.g.
-
setDoNotTrack
(enable)¶ When enabled it will disable sending tracking requests.
Deprecated since version 16.17: This mechanism is phased out in favor of anonymous tracking. You can check how to set it up here.
Arguments: - enable (boolean) – Required When set to true, no tracking tracking requests will be sent.
Example of usage:
_paq.push(["setDoNotTrack", true]);
jstc.setDoNotTrack(true);
-
killFrame
()¶ Checks if tracked page is displayed from inside of a frame and it’ll replace browser URL with tracked page URL in such cases (displaying page inside a frame can be a phishing scam).
Deprecated since version 16.17: It’ll be removed in future versions since it falls outside of JSTC main use case (page tracking).
Example of usage:
_paq.push(["killFrame"]);
jstc.killFrame();
-
redirectFile
(url)¶ Checks if tracked page is displayed from a local file (URL displayed by browser starts with
file:///
) and replaces browser URL with provided URL in such cases.Deprecated since version 16.17: It’ll be removed in future versions since it falls outside of JSTC main use case (page tracking).
Arguments: - url (string) – Required URL that should be loaded.
Example of usage:
_paq.push(["redirectFile"]);
jstc.redirectFile();
-
getNumTrackedPageViews
()¶ Returns a number of page views tracked so far without loading new page. Traditional sites will always show
1
so it’s mostly useful on SPA pages that usetrackPageView()
without loading a new page.Returns: Number of page views tracked so far without loading new page Return type: number Example of usage:
_paq.push([function() { console.log(this.getNumTrackedPageViews()); }]);
console.log(jstc.getNumTrackedPageViews());
-
getConfigIdPageView
()¶ Returns current page view ID. This value is generated with each use of
trackPageView()
. If new value is different ten last value, then JSTC is currently tracking a new page.Returns: Page view ID (e.g. "abCdE1"
)Return type: string Example of usage:
_paq.push([function() { console.log(this.getConfigIdPageView()); }]);
console.log(jstc.getConfigIdPageView());
-
trackHeartBeat
()¶ Sends heartbeat event manually. This heartbeat event will follow rules that are used in other heartbeat events (e.g. it’ll be sent only if tracked page has focus).
Deprecated since version 16.17: It was used to sent event that would extend visitor session but internal rules on when heartbeat could be sent could cause confusion when event was or wasn’t sent. Since introduction of the
ping()
method, you should use that instead.Example of usage:
_paq.push(["trackHeartBeat"]);
this.trackHeartBeat();
-
setCountPreRendered
(enable)¶ Sets prerender event sending policy. If enabled, the prerender will send events immediately. Otherwise sending events will be delayed until the page will be displayed to the viewer.
Arguments: - enable (boolean) – Required Prerender event sending policy (e.g.
true
)
Example of usage:
_paq.push(["setCountPreRendered", true]);
jstc.setCountPreRendered(true);
- enable (boolean) – Required Prerender event sending policy (e.g.