Documentation

Documentation

Installing and configuring the Web-SDK

The Web-SDK automatically collects visitor behavior on the site: pageviews, clicks, interaction with forms and fields, activity, scrolling, tab switching, and, on demand, session recording (rrweb). The data goes to your Rockstat server via sendBeacon or fetch.

Events are combined into sessions right in the browser and classified by source: advertising, organic, social, partner referrals, referral, internal, and direct. More about sessions. You can add your own events with any set of parameters on top of the automatic ones. Works on desktop and in mobile browsers.

Inserting the code#

The snippet is placed on all pages of the site, as high as possible in <head>. There can be several sites, each distinguished by projectId. The current version of the snippet is in the web-sdk repository.

<script>
  !function (w, d, st, cn, hs, lj, rst, se, he) {
    if(w.rstat4) return; rst = w.rstat4 = function () {
      var a = Array.prototype.slice.call(arguments);
      a.length && a[0] === cn && rst._a(Object(a[1]));
      return rst.doCall ? rst.doCall.call(rst, a) : rst._q.push(a) && 0; };
    rst.push = rst; rst._sv = '5.2.1'; rst._q = [];
    rst._jsl = function (src) {
      se = d.createElement(st); se.async = !0; se.src = src;
      he = d.getElementsByTagName(st)[0]; he.parentNode.insertBefore(se, he); };
    rst._a = function(conf){
      rst._host = conf.server; rst._prefix = conf.pathPrefix || '';
      rst._host && rst._jsl(hs+rst._host+rst._prefix+lj); }
  }(window, document, 'script', 'configure', 'https://', '/lib.js');
  // --- configuration ---
  rstat4('configure', {
    server: 'YOUR_SUBDOMAIN.DOMAIN' // <<< replace
  });
  rstat4('page'); // <<< remove if needed
</script>

The snippet creates a global rstat4 function, queues all calls until the library loads, and, when configure is called with a server parameter, loads https://<server>/lib.js. After loading, the library initializes on DOMContentLoaded and runs the accumulated queue. The whole API is a single function: the first argument is the method name, the rest are its parameters.

The library works only over https. For local development over http, add allowHTTP: true to the configuration.

Minimal configuration#

Only server is required. Everything else has sensible defaults: clicks on links, forms, activity, and scrolling are enabled, session recording is disabled.

rstat4('configure', {
  server: 'stat.example.com',
  projectId: 1,                        // optional, otherwise computed from the domain
  trackClicks: { allClicks: true },    // clicks on any elements, not just links
  trackForms: { encryptionKey: '...' } // encrypt form field values in the browser
});
rstat4('page');

The full list of parameters and the settings for each tracker are described in the section Snippet and configuration.

ParameterData typeDefaultDescription
serverStringnullRequired. Tracker server domain without scheme or path. Example: stat.example.com. lib.js is loaded from it and events are sent to it
pathPrefixString''Path prefix on the server. lib.js and events are requested at URLs like <pathPrefix>/lib.js, <pathPrefix>/band/t4k.json
urlMarkString'band'Path segment for event delivery: /<urlMark>/t4k.json
projectIdNumberdomain hashProject identifier. If not set, it is computed from the page domain, see buildProjectId
allowHTTPBooleanfalseAllow working on http pages. By default the SDK only works over https
allowSendBeaconBooleantrueSend events via navigator.sendBeacon
allowXHRBooleantrueAllow sending via fetch
sessionTimeoutNumber1800Session timeout in seconds: how long without events before a new session starts
lastCampaignExpiresNumber7776000How long the last ad campaign is kept, in seconds (90 days)
initialUidNumber0Initial visitor uid, if it must be set from outside
cookieDomainStringpage domainDomain the cookies are set on
cookiePathString'/'Cookie path
cookiePrefixString'rst4-'Prefix for the names of all cookies the SDK sets
lcPrefixString'rst4:'Prefix for keys in localStorage
trackActivityBoolean, Object{ zeroEvents: false, scrollEvents: true, domEvents: true }Activity and scrolling: the activity and scroll events. Settings in the "Trackers" section
trackClicksBoolean, Object{ allClicks: false }Clicks: link_click and, with allClicks, element_click
trackFormsBoolean, Object{}Forms and fields: form_submit, field_focus, field_blur, field_change, field_invalid
trackPagesBooleanfalseReserved. Automatic URL-change tracking in SPAs is not implemented yet, call page manually
trackRecordBoolean, Object{ autostart: false }Session recording (rrweb)
browserEventsBoolean, Object{ unloadHandlers: true, visibilityHandlers: true }The page_unload and page_visibility events
activateWs, wsServer, wsPathBoolean, String, Stringfalse, null, '/wss'WebSocket transport. Reserved, not used in the current version
pixelSyncBoolean, ObjectfalsePixel interception. Reserved, not used in the current version

Pageviews and SPAs#

The library does not send the page event by itself: call rstat4('page') after configure, and in single-page apps on every route change. In page you can pass data about the page: type, category, product ID.

// React Router, Vue Router, etc.: on every route change
router.afterEach(() => {
  rstat4('page', { type: 'category', name: 'Home goods' });
});

Verifying the installation#

Enable verbose logging in the console and subscribe to outgoing messages:

rstat4('enableLogger');
rstat4('onMessage', function (msg) {
  console.log('rockstat →', msg.name, msg);
});

The console will show lines RST/Tracker: Initializing..., then the session, page, page_loaded events. In the Network tab there should be POST requests to https://<server>/band/t4k.json with a 200 response. Logging can also be enabled before the library loads: window._rst4_logger = true.

The visitor identifier is available after initialization:

rstat4('onReady', function () {
  console.log('uid:', rstat4('getUid'));
});

Installing via GTM#

The loader can be installed via Google Tag Manager, but it is recommended to insert it directly into the site's code:

  1. It will load first and have time to intercept identifier synchronizations with other services.
  2. More "bouncers" who leave before GTM loads will be counted.
  3. The platform runs on your domain, and ad blockers don't cut it off, unlike GTM.

Events from the Data Layer#

In GTM, create a "Custom HTML" tag:

<script>
  var name = ({{category}} || '') + '-' + ({{action}} || '');
  var data = {};
  if ({{category}}) data.category = {{category}};
  if ({{action}}) data.action = {{action}};
  if ({{label}}) data.label = {{label}};
  if ({{value}}) data.value = {{value}};
  rstat4('event', name, data);
</script>

Replace category, action, label, value with your own custom variables.

Building the projectId#

Specifying projectId is optional: without it, it is computed from the page's domain.

  • the www and m subdomains are stripped;
  • if the domain still has three or more levels (aaa.bbb.ru), one level is removed (bbb.ru);
  • a numeric hash is computed from the resulting domain.

You can see the result for any domain in the console:

rstat4('buildProjectId', 'www.shop.example.com')
// → ['example.com', 1617632140]

If you have several sites on subdomains of one domain and their data needs to be kept separate, set projectId explicitly: the automatic computation would be the same for them.

What's next#