Onesecondbefore's Analytics JavaScript library lets you collect information about visitors on your website.
It consists of a set of commands (e.g. send
or set
) and
a set of (configuration) options that set certain values or change the library's behaviour.
Onesecondbefore's Analytics Javascript library is used with the following snippet:
osb(command, ...options)
Where command is a constant string that tells the command queue what it should do and options supply additional information to that command. The following commands are supported:
They are described in more detail below.
Sets or adds additional properties in the payload. The payload will not be sent after a 'set'
or 'add'
command.
Only a subsequent 'send'
will send the hit. Use 'add'
if you want to add the { data ... }
to any pre-existing data rather than overwriting the value.
osb('set', name, { data... }); // Sets an object e.g. page
osb('add', name, { data... }); // Adds an object to an array e.g. ids
osb('set', name, [{ data... }, ...]); // Sets an array of objects, e.g. items
name | type | required | description |
---|---|---|---|
'set' or 'add' | string | yes | Name of command. 'set' to overwrite any existing value; 'add' to append to an already existing value. |
name | string | yes | Which record of the payload would you like to update, supported values are 'consent' , 'event' , 'ids' , 'items' , 'page' . |
{data... } | JS object or JS array | yes | Choose the correct option depending on the value you chose for name : |
Adds the Google Analytics client id to the payload (that will be sent with the next 'sent'
command)
osb('add', 'ids', {
key: '_ga',
value: 'cookie:_ga' // 'GA1.2.123456789.1612345678'
});
Add a product item and add two custom product variables: color and size.
osb('add', 'items', {
id: 'abc123',
category: 'clothing/dresses',
name: 'BlackButterfly',
color: 'green',
size: 'm'
});
Set multiple products in a single command.
osb('set', 'items', [{
id: 'sku123',
name: 'Apple iPhone 14 Pro',
category: 'mobile',
price: 1234.56,
quantity: 1
}, {
id: 'sku234',
name: 'Samsung Galaxy S22',
category: 'mobile',
price: 1034.56,
quantity: 1
}]);
Set and hash an email address. Hashing happens in-memory on the Analytics server.
osb('set', 'ids', [{
key: 'email',
value: 'john.doe@example.com',
hash: true
}]);
If the page has a <meta>
tag like this:
<meta name="article-id" content="12345"/>
Retrieve this information with:
osb('set', 'page', {
'id': 'meta:article-id' // '12345'
});
Retrieve information from an external URL and parse the JSON response to retrieve its value.
osb('set', 'page', {
/* This URL should return a JSON response with a key 'user_id' */
'user_id': 'url:https://api.example.com/getid'
});
Set consent information
//All purposes
osb('set', 'consent', 'all');
//Multiple purposes
osb('set', 'consent', 'necessary,analytics');
//Send the TC string (IAB Europe)
osb('set', 'consent', 'CPUP3OWPUP3OWFjAOBENChCsAP_-AH_-ABpaxK...');
Allows reconfiguration of an existing tracker. This is e.g. required if before cookie consent you're not allowed to store the entire IP address ({ ipSettings: 1 }
), whereas after you're allowed to do so ({ ipSettings: 0 }
).
osb('config', { options... });
name | type | required | description |
---|---|---|---|
'config' | string | yes | Name of command. |
{options...} | JS object | yes | Choose from configuration options |
Change the siteId
for the tracker. It is recommended to label all activity from the same app or website with the same siteId
.
osb('config', {
siteId: 'my.web'
});
Change the IP address and cookie settings default behaviour.
osb('config', {
ipSettings: 3
cookieSettings: 2
});
Below documentation describes the consent possibilities in the regular tracker library, loaded as
osb.min.mjs
. For the banner version look here, for the CMP version, look here.
Verify whether user has given cookie consent. There are two different implementations possible:
If the user has given consent, continue on the same page, otherwise, redirect the browser to a specified cookie consent page where the user can give their consent. If consent has already been given (if there are multiple sites under the same consent page), or the user has given consent, the user is redirected back to the current page with an additional querystring parameter which indicates that the user has given consent or not. If the user gave consent, a first-party cookie will be set.
Contact us to setup the cookie consent template, domain name, DNS and SSL certificate(s).
See here for more information.
If you would like to show a (simple / sticky) cookie bar on every page with buttons to either allow or deny consent. A cookie bar is made visible if no consent has been given on the current website. Two buttons can be added to the cookie bar to allow / deny consent. If (no) consent is given, a first-party cookie will be set and the cookie bar will be hidden. Additionally, a third button can be added with a number of checkboxes to specify which purposes have been consented. These purposes have no relation with the TCF version.
See here for more information.
Load the osb.min.mjs
version of the tracker library.
<script type="module" crossorigin="use-credentials">
import osb from 'https://c.onesecondbefore.com/js/v1/osb.min.mjs';
// --------------------------------------------------^^^^^^^^^^^
osb('config', ACCOUNT_ID, { config options } );
osb('consent', { consent options });
osb('send', 'pageview');
</script>
parameter name | type | required | description |
---|---|---|---|
'consent' | string | yes | Name of command. |
{ consent options } | JS object | yes | Options to configure the consent page, see below. |
consent option | type | required | description |
---|---|---|---|
callback | JS function | no | Callback function(consent, cduid) called after the redirect to the original page where consent was requested.
This callback is fired both for consent accepted and not accepted.
The consent parameter either contains the string "all" or "none" (when the buttons to allow or deny all consents were clicked),
or it contains a string with comma separated purposes that were checked (when the button to save preferences was clicked).
Additionally, the cduid parameter contains the cross-domain user-id as captured on the consentUrl domain name. |
cduidName | string | no | Name of querystring parameter and first-party cookie name for cross-domain user-id added to the URL of the original page where consent was requested, default 'cduid' for the query string parameter and '_osb_cduid' for the cookie name. |
consentName | string | no | Name of querystring parameter and first-party cookie name that stores which consent the user has given consent, default 'consent' for the query string parameter and '_osb_consent' for the cookie name. |
consentUrl | string | yes | URL to redirect browser to page where user gives consent, e.g. 'https://privacy.example.com' . |
osb('config', ACCOUNT_ID, {
// Strip of last octet of IP address
ipSettings: 1,
trackerUrl: 'https://privacy.example.com'
});
osb('consent', {
// Add a ?locale=XY parameter to the consentUrl if you want to localize this page
consentUrl: 'https://privacy.example.com/consent',
callback: function(consent, cduid) {
// When consent has been given, update the IP settings to allow entire IP address
// to be captured
if (consent !== 'none') {
osb('config', {
ipSettings: 0
});
}
});
});
osb('send', 'pageview');
If consent needs to be given by the visitor they might see a flash of content of the current page if it takes some time to execute all the javascript and redirect the user to the consent page. To eliminate this, the following can be used:
osb-cloak
attribute to the body
of the HTML document:<body osb-cloak>
[osb-cloak] > * { display: none; }
/* Optional */
[osb-cloak]::before { content: "Please wait..."; }
osb-cloak
attribute will be removed automatically from the <body>
by osb('consent', ...)
and hence the page is visible.Use this version if your website implements a cookie bar or similar on every page, as demonstrated in the videos below.
The cookie bar has the following requirements:
consentId
, e.g. 'cookiebar'
.show
is added, the cookie bar becomes visible).#cookiebar { display: none; }
#cookiebar.show { display: block; }
<a class="allow">
or <button class="allow">
element the user can click to allow consent.<a class="deny">
or <button class="deny">
the user can click to deny all consent.<a class="save">
or <button class="save">
the user can click to save all consents that were selected using <input type="checkbox" name="purpose">
.When the above conditions are met, the script will verify whether consent has been given, if not the cookie bar will be shown and event listeners will be added to the allow
and optionally to the deny
and save
buttons.
When a button is clicked a first-party cookie is set with the given consent, the cookie bar is hidden again and the optional callback function is executed.
consent option | type | required | description |
---|---|---|---|
consentId | string | yes | HTML id of the cookie bar HTML element, e.g. 'cookiebar' . |
callback | JS function | no | Callback function(consent, cduid) called after the redirect to the original page where consent was requested.
This callback is fired both for consent accepted and not accepted.
The consent parameter either contains the string "all" or "none" (when the buttons to allow or deny all consents were clicked),
or it contains an string with comma separated values of the purposes that were checked (when the button to save preferences was clicked). |
consentName | string | no | Name of first-party cookie used to store consent, default '_osb_consent' . |
As an example, use the following HTML on every page:
<style>
#cookiebar {
display: none;
color: #fff;
background-color: #000;
padding: 15px;
position: fixed;
bottom: 0;
width: 100%;
z-index: 20;
}
#cookiebar.show {
display: block;
}
</style>
<div id="cookiebar">
<p>
Lorem ipsum dolor sit amet
<a href="/link/to/privacy">privacy statement</a>.
</p>
<button class="btn btn-primary allow">OK, give consent</button>
</div>
And the following javascript:
osb('consent', { consentId: 'cookiebar' } );
The cookie bar is then shown if no consent is given.
Below example shows allow
, deny
and save
buttons and various purposes which will be saved.
The values and labels for these purposes are arbitrary, but obvious choices are "necessary"
or "functional"
,
"analytics"
, "marketing"
or "advertising"
, and "social"
.
Note that the <input type="checkbox">
should have name="purpose"
.
It would render as in below screenshot:
<style>
/* Same as example above */
</style>
<div id="cookiebar">
<p>
Lorem ipsum dolor sit amet.
<a href="/link/to/privacy">Privacy policy</a>.
</p>
<p>
<label><input type="checkbox" name="purpose" value="necessary">Necessary</label>
<label><input type="checkbox" name="purpose" value="analytics">Analytics</label>
<label><input type="checkbox" name="purpose" value="marketing">Marketing</label>
<label><input type="checkbox" name="purpose" value="social">Social Media</label>
</p>
<p>
<button class="btn btn-secondary save">Save preferences</button>
<button class="btn btn-secondary deny">Deny all</button>
<button class="btn btn-primary allow">Allow all</button>
</p>
</div>
And the following javascript:
osb('consent', {
consentId: 'cookiebar',
callback: function(consent, cduid) {
if (consent === 'none') {
alert('No consent given');
} else if (consent === 'all') {
alert('All consent given');
} else if (consent?.includes('marketing')) {
alert('Marketing consented');
// ... etc.
}
}
});
[top]Below documentation describes the consent possibilities in the tracker library with support for a customized banner, loaded as
osb-banner.min.mjs
. For the standard version look here, for the CMP version, look here.
Verify whether user has given cookie consent. There are two different implementations possible:
If the user has given consent, continue on the same page, otherwise, redirect the browser to a specified cookie consent page where the user can give their consent. If consent has already been given (if there are multiple sites under the same consent page), or the user has given consent, the user is redirected back to the current page with an additional querystring parameter which indicates that the user has given consent or not. If the user gave consent, a first-party cookie will be set.
Contact us to setup the cookie consent template, domain name, DNS and SSL certificate(s).
See here for more information.
If you would like to show a configurable cookie bar on every page with buttons to either allow or deny consent. A cookie bar is made visible if no consent has been given on the current website. Purposes can be shown to indicate for which consent is given. These purpose name have no relation with the IAB TCF purposes. Buttons are added to allow / deny / save consent. If the user makes a choice, a first-party cookie will be set and the cookie bar will be hidden.
See here for more information.
Load the osb-banner.min.mjs
version of the tracker library.
<script type="module" crossorigin="use-credentials">
import osb from 'https://c.onesecondbefore.com/js/v1/osb-banner.min.mjs';
// ------------------------------------------------- ^^^^^^^^^^^^^^^^^^
osb('config', ACCOUNT_ID, { config options } );
osb('consent', { consent banner options });
osb('send', 'pageview');
</script>
parameter name | type | required | description |
---|---|---|---|
'consent' | string | yes | Name of command. |
{ consent options } | JS object | yes | Options to configure the consent page, see below. |
consent option | type | required | description |
---|---|---|---|
callback | JS function | no | Callback function(consent, cduid) called after the redirect to the original page where consent was requested.
This callback is fired both for consent accepted and not accepted.
The consent parameter either contains the string "all" or "none" (when the buttons to allow or deny all consents were clicked),
or it contains a string with comma separated purposes that were checked (when the button to save preferences was clicked).
Additionally, the cduid parameter contains the cross-domain user-id as captured on the consentUrl domain name. |
cduidName | string | no | Name of querystring parameter and first-party cookie name for cross-domain user-id added to the URL of the original page where consent was requested, default 'cduid' for the query string parameter and '_osb_cduid' for the cookie name. |
consentName | string | no | Name of querystring parameter and first-party cookie name that stores which consent the user has given consent, default 'consent' for the query string parameter and '_osb_consent' for the cookie name. |
consentUrl | string | yes | URL to redirect browser to page where user gives consent, e.g. 'https://privacy.example.com' . |
osb('config', ACCOUNT_ID, {
// Strip of last octet of IP address
ipSettings: 1,
});
osb('consent', {
// Add a ?locale=XY parameter to the consentUrl if you want to localize this page
consentUrl: 'https://privacy.example.com/consent',
callback: function(consent, cduid) {
// When consent has been given, update the IP settings to allow entire IP address
// to be captured
if (consent !== 'none') {
osb('config', {
ipSettings: 0
});
}
});
});
osb('send', 'pageview');
If consent needs to be given by the visitor they might see a flash of content of the current page if it takes some time to execute all the javascript and redirect the user to the consent page. To eliminate this, the following can be used:
osb-cloak
attribute to the body
of the HTML document:<body osb-cloak>
[osb-cloak] > * { display: none; }
/* Optional */
[osb-cloak]::before { content: "Please wait..."; }
osb-cloak
attribute will be removed automatically from the <body>
by osb('consent', ...)
and hence the page is visible.Another option is to show the banner on every page. The user can interact with the page but the banner will only be hidden if they make a consent choice.
osb('config', ACCOUNT_ID, {
// Strip of last octet of IP address
ipSettings: 1,
});
osb('consent', {
title: 'Cookies on example.com',
text: 'We use cookies to ...',
purposes: [{'functional': false}, 'analytics', 'social'],
// ... /* More settings */
callback: function(consent, cduid) {
// When consent has been given, update the IP settings to allow entire IP address
// to be captured
if (consent !== 'none') {
osb('config', {
ipSettings: 0
});
}
}
});
osb('send', 'pageview');
consent option | type | required | description |
---|---|---|---|
backgroundColor | string | no | The background color of the banner, default '#f0f0f0' . |
buttonFont | string | no | Name of the font to use for the buttons. The font should be loaded separately, e.g. by using Google Fonts, default is same as font . |
buttonFontSize | string | no | The font-size in px to use for buttons, default '16px' . |
buttonOutlineBorderColor | string | no | The border-color of the secondary buttons, default secondaryColor . |
callback | JS function | no | Callback function(consent, cduid) called after the redirect to the original page where consent was requested.
This callback is fired both for consent accepted and not accepted.
The consent parameter either contains the string "all" or "none" (when the buttons to allow or deny all consents were clicked),
or it contains an string with comma separated values of the purposes that were checked (when the button to save preferences was clicked). |
consentId | string | no | HTML id of the cookie bar HTML element, e.g. 'cookiebar' . |
cookieStatementUrl | string | no | A link to a cookie statement URL. Added after the text . |
font | string | no | Name of the font to use for the text . The font should be loaded separately, e.g. by using Google Fonts, default 'Open Sans', Arial, Helvetica, 'sans-serif' . |
language | string | no | A two letter ISO-639 language code, default 'en' . Used to translate button texts and purpose names. |
privacyStatementUrl | string | no | A link to a privacy statement URL. Added after the text . |
primaryColor | string | no | The primary color of the title, checkboxes and "Allow all" button background, default '#0f6600' . |
primaryHoverColor | string | no | The color of the checkboxes and "Allow all" button background when hovered, default '#0f7700' . |
primaryTextColor | string | no | The color of the text, default '#ffffff' . |
primaryTextHoverColor | string | no | The primary color of the text when hovered, default primaryTextColor . |
purposes | string array | yes | An array of one or more of the following purpose names: In this example |
roundedCorners | boolean | no | Whether rounded corners should be applied to the buttons and banner, default false . |
secondaryColor | string | no | The background color of the other buttons, default '#a0a0a0' . |
secondaryHoverColor | string | no | The background color of the other buttons when hovered, default '#b0b0b0' . |
secondaryTextColor | string | no | The text color of the other buttons, default '#333333' . |
secondaryTextHoverColor | string | no | The text color of the other buttons when hovered, default secondaryTextColor . |
text | string | yes | A single paragraph of text explaining why consent needs to be given. |
textColor | string | no | The color of the text, default '#333333' . |
textFontSize | string | no | The font-size of the text in px, default '12px' . |
title | string | no | The title to show in the consent banner. |
titleFont | string | no | Name of the font to use for the title . The font should be loaded separately, e.g. by using Google Fonts, default is same as font . |
titleFontSize | string | no | The font-size of the title in px, default '24px' . |
width | number | no | The width of the banner (in px, default 960 ). |
zIndex | number | no | The z-index of the consent banner, default 2000 .
|
osb('consent', {
consentId: 'cookiebar',
title: 'This site uses cookies',
text: 'We use cookies to...',
purposes: [{ functional: false }, 'analytics', 'social' ],
privacyStatementUrl: 'https://www.example.com/privacy',
});
The cookie bar is then shown if no consent is given.
[top]Below documentation describes the consent possibilities in the IAB TCF v2.2 tracker library, loaded as
osb-cmp.min.mjs
. For the standard version, look here, for the banner version look here.
Verify whether user has given cookie consent using the IAB TCF v2.2 standard.
Load the osb-cmp.min.mjs
version of the tracker library to include IAB TCF 2.2 compatibility.
<script type="module" crossorigin="use-credentials">
import osb from 'https://c.onesecondbefore.com/js/v1/osb-cmp.min.mjs';
// ------------------------------------------------- ^^^^^^^^^^^^^^^
osb('config', ACCOUNT_ID, { config options } );
osb('consent', { consent options });
osb('send', 'pageview');
</script>
parameter name | type | required | description |
---|---|---|---|
'consent' | string | yes | Name of command. |
{ consent options } | JS object | yes | Options to configure the consent page, see below. |
consent option | type | required | description |
---|---|---|---|
callback | JS function | no | Callback function(consent, cduid) called after the redirect to the original page where consent was requested. This callback is fired both for consent accepted and not accepted. consent is a JavaScript object with the following fields:
|
configUrl | string | yes | URL to retrieve CMP configuration from. Contact us for guidance. |
show | boolean or number or function returning a boolean or number. | no | If null (default), show the CMP if consent not yet given, don't show when consent already given.If true , show CMP, regardless of whether consent has been given or not.If false , do not show CMP, regardless of whether consent has been given or not.If 1 surface the homepage of the CMP.if 2 surface the purposes and legitimate interests list.if 3 surface the vendor list. |
If visitor consented to purpose 1
, update the ipSettings
configuration parameter.
// Script loaded from "osb-cmp.min.mjs"
osb('config', ACCOUNT_ID, {
ipSettings: 1
});
osb('consent', {
configUrl: 'https://privacy.example.com/osb-config.json',
callback: function(consent, cduid) {
// Now consent is given, update the IP settings to allow entire IP address
// to be captured
if (consent.purposes && consent.purposes.includes(1)) {
// Consent should include purpose 1 (Store and/or access information on a device)
osb('config', {
ipSettings: 0
});
}
});
});
osb('send', 'pageview');
Add a LinkedIn pixel if purposes 1, 8 and 15 have been consented.
const LINKEDIN_PARTNER_ID = '1234567';
function linkedin(partnerId) {
window._linkedin_data_partner_ids = window._linkedin_data_partner_ids || [];
window._linkedin_data_partner_ids.push(partnerId);
const s = document.getElementsByTagName("script")[0];
const b = document.createElement("script");
b.async = true;
b.src = "https://snap.licdn.com/li.lms-analytics/insight.min.js";
s.parentNode.insertBefore(b, s);
}
// Script loaded from "osb-cmp.min.mjs"
osb('config', ACCOUNT_ID);
osb('consent', {
configUrl: 'https://privacy.example.com/osb-config.json',
callback: function(consent, cduid) {
if (consent && consent.purposes && consent.purposes.includes(1) &&
consent.purposes.includes(8) && consent.purposes.includes(15)) {
linkedin(LINKEDIN_PARTNER_ID);
}
}
});
osb('send', 'pageview');
// Similar with more ES2016 features:
osb('config', ACCOUNT_ID);
osb('consent', {
configUrl: 'https://privacy.example.com/osb-config.json',
callback: (consent, cduid) => {
if ([1,8,15].every((p) => { return consent?.purposes?.includes(p) }) {
linkedin(LINKEDIN_PARTNER_ID);
}
}
});
osb('send', 'pageview');
// Or a function determining whether the CMP should be shown:
osb('config', ACCOUNT_ID);
osb('consent', {
configUrl: 'https://privacy.example.com/osb-config.json',
show: function() {
return confirm('Click Yes if you want to show the CMP');
}
});
// Or check whether a Bot is visiting the site and then don't show CMP:
osb('config', ACCOUNT_ID);
osb('consent', {
configUrl: 'https://privacy.example.com/osb-config.json',
show: () => {
if (navigator.userAgent.indexOf('Bot') >= 0) {
// Don't show if it's a Bot
return false;
} else {
// Default behaviour; show if no consent given, hide if already given
return null;
}
}
});
Open CMP at a particular "page" or "tab":
<!-- Assume that osb object has already been loaded previously -->
<a href="#" onclick="osb('consent', { show: 1 })">Show cookie settings</a>
<a href="#" onclick="osb('consent', { show: 3 })">Show vendors</a>
Enables / disables additional debug logging in the console.
// Additional debugging information will be displayed in the JavaScript developer console.
osb('debug', enabled);
parameter name | type | required | description |
---|---|---|---|
'debug' | string | yes | Name of command. |
enabled | boolean | no | Default value is true . Use true to enable debug logging, false to disable. |
Switch on debug information in JavaScript Console.
osb('debug');
Switch off debug information in JavaScript Console.
osb('debug', false);
Additionally, it is possible to switch on debug mode automatically by specifying a querystring parameter ?_osb_debug
on
the page which loads the OSB JS library. This enables debugging on the page without the need to change the HTML template or access to
the browser's JavaScript console. So, if the JS library is loaded on www.example.com
, specify www.exempla.com?_osb_debug
to enable debugging.
Returns the content of the payload of a particular tracker.
osb('get', callback);
osb('get', name, callback);
parameter name | type | required | description |
---|---|---|---|
'get' | string | yes | Name of command. |
name | string | yes | Name of payload you'd like to see, 'event' , 'page' , 'ids' , 'consent' . |
callback | JS function | yes | Callback function(payload) that receives the payload. |
Get consent
// Return consent
osb('get', 'consent', (purposes) => {
// ['marketing', 'social', ... ]
console.log(JSON.stringify(purposes));
});
Get the payload only of the event
object.
// Return payload only for "event"
osb('get', 'event', (payload) => {
console.log(JSON.stringify(payload));
});
Retrieve a profile based upon the current (cross-domain) user id cookie. A profile is a list of strings which translate into aspects known about the visitor, like viewer preference, location, age group, etc.
Based upon external (batch) processes these profiles can be created and updated using information gathered while the user is browsing the website.osb('profile', callback);
parameter name | type | required | description |
---|---|---|---|
'profile' | string | yes | Name of command. |
callback | JS function | no | Callback function that will be called with the cross-domain user id and public profile of the visitor (an array of strings). |
Get the user profile and log it in the JavaScript console of the browser. Handy for development purposes.
osb('profile', function(cduid, profile) {
/* Profile is a list of strings which translate into various aspects */
console.log(`Profile for ${cduid} = ${JSON.stringify(profile)}`);
});
Get the user profile and change the HTML accordingly. Typical use-case for onsite targeting.
osb('profile', function(cduid, profile) {
/* Change the HTML of the current page, based on various aspects of the profile */
if (profile && profile.indexOf('youth') >= 0) {
changeHTML(profile);
}
});
Removes additional payload data. It will no longer be sent along with requests.
osb('remove', name);
parameter name | type | required | description |
---|---|---|---|
'remove' | string | yes | Name of command. |
name | string | yes | Name of object or array to remove. |
Sets and then removes the ids object. Use this if you only want the ids to be sent in a single hit.
osb('set', 'ids', { ... });
osb('send', 'ids');
osb('remove', 'ids');
Resets all payloads.
osb('reset');
parameter name | type | required | description |
---|---|---|---|
'reset' | string | yes | Name of command. |
Resets all payloads.
osb('set', 'ids', { ... });
osb('set', 'page', { ... });
osb('reset');
Sends a hit to the analytics server, like a pageview
or an event
.
osb('send', 'pageview', { options });
osb('send', 'event', { options });
//- osb('send', 'action', subtype, { options });
osb('send', 'ids', { options });
osb('send', 'viewable_impression', { options });
// In beta contact Onesecondbefore first
osb('send', 'aggregate', name, aggregate, value, scope);
parameter name | type | required | description |
---|---|---|---|
'send' | string | yes | Name of command. |
type | string | yes | Specifies the type to send. You can use:
The type will be stored in column |
name | string | yes if type equals 'aggregate' | Name of the aggregation as it will be saved in the record. |
aggregate | aggregate function | yes if type equals 'aggregate' | Name of the aggregate function. Currently supported: 'max' , 'min' , 'count' , 'sum' , 'avg' . |
value | number | yes if type equals 'aggregate' | Value that should be used by the aggregate function. |
scope | 'pageview' or 'event' | yes if type equals 'aggregate' , default 'pageview' . | Scope or group by of the aggregate function. Must be one of: If set to If set to |
{ options } | JS object | no | Contains type specific data. If you want to set additional payloads, or use them in multiple osb('send', ...) commands, then use the osb('set', ... ) command. Choose one of the following: |
Set additional payload from a <meta>
tag on the page. If the page contains:
<meta name="article-id" content="12345">
You can get the information with:
osb('send', 'pageview', {
'id': 'meta:article-id' // '12345'
});
Add the Google Analytics client id to the ids array and sends it immediately. Will show up with hit_type='ids'
in hits table.
osb('send', 'ids', {
key: '_ga',
value: 'cookie:_ga' // 'GA1.2.123456789.1612345678'
});
Set multiple products in a single command and send those items together with the action.
Typically on a thank-you page during e-commerce checkout.
The value affiliation
will be added to the data array of objects.
osb('set', 'items', [{
id: 'sku123',
name: 'Apple iPhone 14 Pro',
category: 'mobile',
price: 1234.56,
quantity: 1
}, {
id: 'sku234',
name: 'Samsung Galaxy S22',
category: 'mobile',
price: 1034.56,
quantity: 1
}]);
osb('set', 'action', {
id: 'abcd1234',
revenue: 2269.12,
tax: (2269.12 * 0.21),
shipping: 100,
affiliation: 'partner_funnel'
});
//All information should be send with the pageview
osb('send', 'pageview');
(In beta, contact Onesecondbefore before use) Aggregate command to track scrolldepth on a page.
osb('send', 'aggregate', 'scrolldepth', 'max', 0.80, 'pageview')
(In beta, contact Onesecondbefore before use) Aggregate command to track the duration of a video.
osb('send', 'aggregate', 'video_duration', 'max', 34, 'event',
{
category: 'videos', // Must be same as corresponding event
action: 'start', // Must be same as corresponding event
label: 'funny cat movie' // Must be same as corresponding event
})
Returns the payload and config the tracker as a JSON object. Useful for debugging.
osb('show', function (response) {
console.log(JSON.stringify(response));
});
name | type | required | description |
---|---|---|---|
'show' | string | yes | Name of command. |
callback | JS function | No | Callback function(response) with the response with all the data. If not specified will output the response to the browser's console. |
Shows the meta information of the current tracker.
// Display everything in JavaScript developer console
osb('show');
// Display only the version
osb('show', function(response) {
console.log(`Version = ${response.version}`);
});
Retrieves the cross-domain user-id (or domain user-id if not available) and calls a function with this UID as a parameter.
osb('uid', callback);
parameter name | type | required | description |
---|---|---|---|
'uid' | string | yes | Name of command. |
callback | function | no | Callback function(uid) that receives cross-domain or domain user-id as a parameter. If no callback is specified, the UID will be logged to the console. |
Retrieves the user_id
.
osb('uid', function(uid) {
console.log('UID = ' + uid);
}):
There are two categories of options:
Configuration options can only be set with the config command. They are meant to configure the tracker and are not stored in your database.
osb('config', {
accountId: 'act123',
cookieDomain: 'mydomain.com',
cookieNamePrefix: '_osb_',
cookiePath: '/',
cookieSettings: 1,
siteId: 'mygreatsite',
forceGET: false,
ipSettings: 0,
userCookieTimeout: 31536000
googleConsentMode: function(purposes) {
return {
ad_storage: purposes.includes('all') || purposes.includes('advertising') ? 'granted' : 'denied',
// ...
}
},
trackExitLinks: true,
trackExitIgnoredDomains: ['site1.com','site2.com'],
trackCoreWebVitals: {
CLS: true, // Specify which metrics to include
FIP: false,
attribution: true, // Add attribution details for each metric
timeout: 2000, // Send CWV hit after 2 seconds instead of default 5 seconds.
},
});
property | type | default value | description |
---|---|---|---|
accountId | string | Account ID used to store your data | Contact us for guidance. |
cookieDomain | string | Depends on domain name / host HTTP request header | First-party cookie domain. Default is final two '.' separated parts of the requesting domain name, e.g. when your site is www.company.com , the cookieDomain would be .company.com . |
cookieNamePrefix | string | '_osb_' | Prefix of all OSB Analytics cookie names set first-party on your own website. The cookies set on the trackerUrl domain name always have an '_osb_' prefix. |
cookiePath | string | '/' | Cookie path. |
cookieSettings | numeric | 1 | Which cookie settings to use, see below for an overview. |
forceGET | boolean | false | True forces the tracker to use an HTTP GET rather than POST method. |
ipSettings | numeric | 0 | Which IP settings to use, see below for an overview. |
siteId | string | Max 64 chars that match regexp: ^[A-Za-z0-9._-]+$ | Site ID, to distinguish which site sends the hit. Especially useful if your site spans multiple domain names or you want to categorize hits of the same domain. |
trackCoreWebVitals | boolean or object |
If using an object:
| (In Beta) Whether Core Web Vitals (CWV) performance metrics should be tracked in browsers that support it, e.g. Chrome.
If set to true, all CWV metrics (CLS FCP (First Contentful Paint), INP (Interaction to Next Paint), LCP (Largest Contentful Paint), TTFB (Time To First Byte) will be sent.
Additionally, if using an object, individual metrics can be disabled (by specifying the name of the metric ({ CLS: true, FCP: false, INP: true, LCP: false, TTFB: true }
and attribution details can be specified which will send (much) more details, by specifying { attribution: true } .
By default the CWV hit is sent 5s after the page was loaded. This can be changed by specifying a timeout in ms: { timeout: 2000 } .
All core web vital information is stored as hit_type ='performance' and event.category (or EVENT__CATEGORY in Snowflake or event__category in ClickHouse)='CoreWebVitals' . All metrics are stored as key-value pairs in the data array.
|
trackExitLinks | boolean | false | If Onesecondbefore should automatically track exit links. If set to true , Onesecondbefore will parse the page and replace all links that start with https:// or http:// with a redirect link.
If an exit link is clicked, it will first redirect the user to the tracker URL, count the exit link and then redirect the user to the original landing page.
Exit links are stored in the database as hit_type ='event' and event.category (or EVENT__CATEGORY in Snowflake or event__category in ClickHouse)='ExitLink' . |
trackExitIgnoredDomains | array of domains | [] | If trackExitLinks is set to true , this config option is used to exclude the exit links that have a domain in this list. E.g. if a page contains a link to https://www.onesecondbefore.com and
the list contains ["onesecondbefore.com"] it will not replace the existing link with a redirect URL. |
trackerUrl | string | 'https://c.onesecondbefore.com' | Tracker URL endpoint. If the JS library is loaded from your own (sub) domain name, that is used instead. |
userCookieTimeout | numeric | 31536000 | Time-out of the first-party cookies in seconds. Default is 1 year. |
googleConsentMode | JS function | function(purposes) {
return {
ad_storage: purposes.includes('all') || purposes.includes('advertising') ? 'granted' : 'denied',
...
}
} | Read our article on Google Consent Mode here. |
cookie settings | description |
---|---|
0 or 1 | Save cross-domain user id first-party using JavaScript (default). |
2 | Do not save cross-domain user id first-party using JavaScript. |
3 | Do not save any cookies, neither first nor third-party. |
IP settings | description |
---|---|
0 | Entire IP address will be saved. |
1 | Last octet of the IPv4 address will be removed before storing (but used for country, city matching). E.g. 12.34.56.78 will be stored as 12.34.56.0 . |
2 | Entire IP address will be saved in a hashed format. |
3 | IP address will be saved as 'hidden' . |
Data options can be set along its corresponding command (event, ids, items or pageview) or set
with the set or add commands. With set
, no hit is sent to the server, whereas with send
a hit is sent to the server.
By prefixing a data value it is possible to substitute certain values before they are being set in the respective payload. The following prefixes are supported:
prefix | description |
---|---|
'cookie:' | Retrieve the value of the cookie with the given name. If the cookie is not set, the entire key/value pair is removed from the payload. |
'meta:' | Retrieve the content attribute of the <meta> element with the given name . If not found, the entire key/value pair is removed from the payload. |
'local:' | Retrieve a value from localStorage. |
'query:' | Extract the querystring parameter with the given name. |
'session:' | Retrieve a value from sessionStorage. |
'url:' | If the URL returns an HTTP 200 OK status and a JSON response, the value of the key in this response. |
Use a JS function | Instead of prefixing the value string, provide a JavaScript function() that will return the value. |
// Retrieve Google Analytics cookie
osb('add', 'ids', {
key: '_ga',
value: 'cookie:_ga' // 'GA1.2.123456789.1612345678'
});
// Given a <meta name="article-id" content="12345"> tag, retrieve its value
osb('send', 'pageview', {
'id': 'meta:article-id' // '12345'
});
// local/session storage
sessionStorage.setItem('username', 'john.doe@example.com');
localStorage.setItem('name', 'John Doe');
osb('add', 'ids', {
name: 'local:name',
email: 'session:email'
});
// Given a URL /search?q=iPhone
osb('send', 'pageview', {
search_term: 'query:q' // iPhone
});
// Given a response {"some_id":1234567890}
osb('set', 'ids', {
some_id: 'url:https://api.example.com/get_some_id'
});
// Given a JS function
osb('set', 'page', {
random: function() { return Math.random(); }
});
Contains the options of an action
. Actions are typically used to track ecommerce actions like purchase or checkout. It will populate the action object (Snowflake) or struct (BigQuery) in the Analytics hits table.
The following commands support the parameters:
name | type | default value | description |
---|---|---|---|
action | string | null | Name for the action. E.g. purchase, checkout, newsletter_subscription, etc. |
id | string | null | Order or transaction id. |
revenue | float | null | Total revenue amount. |
shipping | float | null | Shipping amount. |
tax | float | null | Tax amount. |
currency_code | string | null | Contains the currency code. We recommend using the ISO-4217 ISO codes. |
any other | string | null | Custom data key/value pairs (up to 50 per action). Will be stored in the data array of the Analytics hits table. |
Contains the consent value.
The following commands support the parameters:
The value can be sent as a string or an array, not as a JavaScript object as with other payload data.
type | default value | description |
---|---|---|
array or string | null | Consent value like 'all' or ['necessary','advertising'] or a valid TC String (IAB Europe) from us as a provider, like: CPUP3OWPUP3OWFjAOBENChCsAP_-AH_-ABpaxK... |
Contains the options of an event. Will populate the event object (Snowflake) or struct (BigQuery) in the Analytics tables.
The following commands support the parameters:
hit_type=event
.name | type | default value | description |
---|---|---|---|
category | string | null | Contains the event category, e.g. 'video' . |
action | string | null | Contains the event action, e.g. 'play' . |
label | string | null | Contains the event label, e.g 'funny_cat_12345.mov' . |
value | number | null | Contains the event value, e.g. 0 . |
interaction | boolean | null (or true) | Contains whether the event should be considered an interaction. Only if true , will the hit be sessionized. |
any other | string | null | Custom data key/value pairs (up to 50 per hit). Will be stored in the data array of the Analytics hits table. |
Contains the options of ids. Will populate the ids
array in the Analytics tables.
The following commands support the parameters:
ids
object to the ids arrayhit_type=ids
.name | type | default value | description |
---|---|---|---|
key | string | null | Contains the key of the id, e.g. _ga . |
value | string | null | Contains the id, e.g. 123456789.987654321 . |
label | string | null | Use this if you want to use the same key in different situations. E.g. a _ga cookie value for different accounts on the same web page. |
hash | boolean | null | Use this if you want Analytics to hash your value in-memory before storing it in the database, e.g. for
email addresses or phone numbers. Hashing is done with SHA256(salt + ':' + value) where
salt is account specific and can be retrieved from the
Onesecondbefore Console
(with proper permissions).
So if the salt is OSB and the email address is test@onesecondbefore.com, use this statement in BigQuery to calculate the hash: SELECT TO_HEX(SHA256('OSB:test@onesecondbefore.com'))
(which would be 'c2ddd2d48ea0889b95b6e2750624b9690deb4feacdc6ef81195b17138c989496' ).
|
Contains the options of items. Will populate the items
array in the Analytics tables.
The following commands support the parameters:
item
object to the items arrayname | type | default value | description |
---|---|---|---|
id | string | null | Product id or sku. |
name | string | null | Product name. |
category | string | null | Product category. |
price | float | null | Product price. |
quantity | float | null | Product quantity. |
any other | string | null | Custom data key/value pairs (up to 50 per action). Will be stored in the data array of the Analytics hits.action.items.data table. |
Contains the options of a page. Will populate the page object (Snowflake) or struct (BigQuery) in the Analytics tables.
The following commands support the parameters:
hit_type=pageview
.On-site search tracks all KPI's needed for deep insights in how users interact with your on-site search engine. As an extra feature we recommend to add a query parameter to each result
link that tracks the number of the search result. The first search result should get number 1, the second result number 2, etc., etc. The
query parameter is oss_result
. Onesecondbefore picks up the parameter and this enables you to see which search result was clicked in combination with
keyword and search filters. Below is a simple example that contains oss_result
.
<h1>Your results for "Reggae":</h1>
<a href="/product/steel-pulse?oss_result=1">Bob Marley</a><br/>
<a href="/product/steel-pulse?oss_result=2">Steel Pulse</a><br/>
<a href="/product/steel-pulse?oss_result=3">Bunny Wailer</a><br/>
<a href="/product/steel-pulse?oss_result=4">The Gladiators</a><br/>
name | type | default value | description |
---|---|---|---|
title | string | JS: document.title | Title of the page. |
id | string | null | Unique id of the page in the Content Management System. |
url | string | JS: location.href | URL of the page, in case you want to override the default. If the value starts with the protocol (e.g. http), it is considered a full URL. If the value starts with a slash (/), everything from the path (including query string and fragment) will be overwritten. If the value starts with a question mark (?), everything after the query string (including the fragment) will be overwritten. If the value starts with a hash (#), everything after the fragment will be overwritten. |
referrer | string | JS: document.referrer | URL of the referrer, in case you want to override the default. If the value starts with the protocol (e.g. http), it is considered a full URL. If the value starts with a slash (/), everything from the path (including query string and fragment) will be overwritten. If the value starts with a question mark (?), everything after the query string (including the fragment) will be overwritten. If the value starts with a hash (#), everything after the fragment will be overwritten. |
oss_keyword | string | null | On-site search query / keyword. More info on on-site search. |
oss_category | string | null | On-site search category. More info on on-site search. |
oss_total_results | integer | null | On-site search total number of search results. More info on on-site search. |
oss_results_per_page | integer | null | On-site search number of search results per result page. More info on on-site search. |
oss_current_page | integer | null | On-site search result current page number. More info on on-site search. |
any other | string | null | Custom data key/value pairs (up to 50 per action). Will be stored in the data array of the Analytics hits table. |