Skip to content

TD JS SDK APIs

Treasure(config)

Creates a new Treasure logger instance. If the database does not exist and you have permissions, it will be created for you.

Core Parameters

NameTypeDescription
config.databasestringdatabase name, must consist only of lower case letters, numbers, and _, must be longer than or equal to 3 chars, and the total length of database and table must be shorter than 129 chars.
config.writeKeystringwrite-only key, get it from your user profile
[config.pathname]stringpath to append after host. Default: /js/v3/events
[config.host]stringhost to which events get sent. Default version 4.0: records.in.treasuredata.com. Default version 3.1: in.treasuredata.com
[config.development]booleantriggers development mode which causes requests to be logged and not get sent. Default: false
[config.logging]booleanenable or disable logging. Default: true
[config.globalIdCookie]stringcookie td_globalid name. Default: _td_global
[config.startInSignedMode]booleanTell the SDK to default to Signed Mode if no choice is already made. Default: false
[config.jsonpTimeout]numberJSONP timeout (in milliseconds) Default: 10000
[config.storeConsentByLocalStorage]booleanTell the SDK to use localStorage to store user consent. Default: false

Track/Storage Parameters

NameTypeDescription
[config.clientId]stringuuid for this client. When undefined it will attempt fetching the value from a cookie if storage is enabled, if none is found it will generate a v4 uuid
[config.storage]object or stringstorage configuration object. When none it will disable cookie storage
[config.storage.name]stringcookie name. Default: _td
[config.storage.expires]integercookie expiration in seconds. When 0 it will expire with the session. Default: 63072000 (2 years)
[config.storage.domain]stringcookie domain. Default: result of document.location.hostname

Server Side Cookie Parameters

NameTypeDescription
[config.useServerSideCookie]booleanenables/disable using ServerSide Cookie. Default: false
[config.sscDomain]stringDomain against which the Server Side Cookie is set. Default: window.location.hostname
[config.sscServer]stringhostname to request server side cookie from. Default: ssc.${sscDomain}

Personalization Parameters

NameTypeDescription
[config.cdpHost]stringThe host to use for the Personalization API. Default: cdp.in.treasuredata.com

Consent Parameters

NameTypeDescription
[config.consentManager]objectConsent Manager configuration, setup along with the TD JavaScript SDK initialization.Every time when a page is loaded, TD JS Consent Extension will check the consent expiry date and if there's any expired consent, then the expiredConsentCallback is triggered. It also updates status of the expired consent to expired
[config.consentManager.storageKey]stringName of the local storage. Default: td_consent_preferences
[config.consentManager.consentTable]stringName of the consent table. Default: td_cm_consent
[config.consentManager.contextTable]stringName of the context table. Default: td_cm_context
[config.consentManager.issuer]stringName of the consent management platform. Default: treasuredata
[config.consentManager.dateFormat]stringDate format string. Default: YYYY-MM-DD
[config.consentManager.successConsentCallback]functionSuccessful saving consent callback
[config.consentManager.failureConsentCallback]functionFailed to save consent callback
[config.consentManager.expiredConsentsCallback]functionExpired consent callback
[config.consentManager.expiredConsentsCallback]functionExpired consent callback

Returns:

  • Treasure logger instance object

Example:

var foo = new Treasure({
  database: 'foo',
  writeKey: 'your_write_only_key'
});

Treasure#addRecord(table, record, success, error)

Sends an event to Treasure Data. If the table does not exist it will be created for you.

Records will have additional properties applied to them if $global or table-specific attributes are configured using Treasure#set.

Warning:

This function will not send td_ip, td_client_id, td_global_id automatically, so if you want to send those information along with this function you have to do it manually, as follows:

td.ready(function () {
   td.set('$global', 'td_ip', 'ip value');
   td.set('$global', 'td_client_id', td.getTrackValues().td_client_id);
   td.set('$global', 'td_global_id', 'global id value');

   td.addRecord(...)
});

Parameters:

  • table : String (required) - table name, must consist only of lower case letters, numbers, and _ (underscore), must be longer than or equal to 3 chars, the total length of database and table must be shorter than 129 chars.
  • record : Object (required) - Object that will be serialized to JSON and sent to the server
  • success : Function (optional) - Callback for when sending the event is successful
  • error : Function (optional) - Callback for when sending the event is unsuccessful

Example:

var company = new Treasure({...});

var sale = {
  itemId: 100,
  saleId: 10,
  userId: 1
};

var successCallback = function () {
  // celebrate();
};

var errorCallback = function () {
  // cry();
}

company.addRecord('sales', sale, successCallback, errorCallback);

Treasure#fetchGlobalID(success, error, forceFetch, options)

This function calls the endpoint specified in the host configuration file.

Parameters:

  • success : Function (optional) - Callback for when sending the event is successful
  • error : Function (optional) - Callback for when sending the event is unsuccessful
  • forceFetch : Boolean (optional) - Forces a refetch of global id and ignores cached version (default false)
  • options : Object (optional) - Cookie options

Cookie options:

{
  path: '/',
  domain: 'abc.com',
  secure: true|false,
  maxAge: Number | String | Date,
  sameSite: 'None | Lax | Strict'
}

Note: If you set the sameSite value to None, the Secure property of the cookie will be set to true (it overwrites the secure option). More details on SameSite cookies.

Example:

var td = new Treasure({...})

var successCallback = function (globalId) {
  // celebrate();
};

var errorCallback = function (error) {
  // cry();
}

td.fetchGlobalID(successCallback, errorCallback)

// with cookie options
td.fetchGlobalID(successCallback, errorCallback, false, {
  path: '/',
  secure: true,
  maxAge: 5 * 60 // 5 minutes,
  sameSite: 'None'
})

Treasure#fetchUserSegments(options, success, error)

Parameters:

  • options : Object (required) - User Segment object
    • options.audienceToken : String or Array (required) - Audience Token(s) for the userId
    • options.keys : Object (required) - Key Value to be sent for this segment
  • success : Function (optional) - Callback for receiving the user key and segments
  • error : Function (optional) - Callback for when sending the event is unsuccessful

Example:

var td = new Treasure({...})

var successCallback = function (values) {
  /* values format => [... {
    key: {
      [key]:value
    },
    values: ["1234"],
    attributes: {
      age: 30
    },

  } ... ]*/
  // celebrate();
};

var errorCallback = function (error) {
  // cry();
};

td.fetchUserSegments({
  audienceToken: ['token1', 'token2'],
  keys: {
    someKey: 'someValue',
    someOtherKey: 'someOtherValue',
  }
}, successCallback, errorCallback)
info

This feature is not enabled on accounts by default. Contact Technical Support or your Customer Success representative to enable it.

fetchPersonalization(config, data, successCallback, errorCallback)

NameTypeDescription
configobjectconfiguration object
config.endpointstringPersonalization endpoint
config.databasestringDatabase name
config.tablestringTable name
config.tokenstringPersonalization token
dataobject(Optional) payload to send with the request
successCallbackfunctionCallback for successful request
errorCallbackfunctionCallback for failed quest

Example:

var td = new Treasure({...})
var successCallback = function (values) {
  //values format => {
    "offers": {
      "offer": {
        "attributes": {
          "first_name": "test",
          "nickname": "tet"
        },
        "batch_segments": 55352
      }
     }
   }

  // celebrate();
}
var errorCallback = function (error) {
  // cry();
}

td.fetchPersonalization({
  endpoint: 'endpoint',
  database: 'database',
  table: 'table',
  token: 'personalization token'
}, null, successCallback, errorCallback)
info

Any information that is marked as sensitive information will be excluded from the response.

Treasure#blockEvents

Block all events from being sent to Treasure Data.

Example:

var td = new Treasure({...})
td.trackEvent('customevent')
td.blockEvents()
td.trackEvent('willnotbetracked')

Treasure#unblockEvents

Unblock all events; events will be sent to Treasure Data.

Example:

var td = new Treasure({...})
td.blockEvents()
td.trackEvent('willnotbetracked')
td.unblockEvents()
td.trackEvent('willbetracked')

Treasure#areEventsBlocked

Informational method, expressing whether events are blocked or not.

Example:

var td = new Treasure({...})
td.areEventsBlocked() // false, default
td.blockEvents()
td.areEventsBlocked() // true

Treasure#setSignedMode

Allow sending Personally Identifying Information over the wire: td_ip, td_client_id, and td_global_id.

Example:

var td = new Treasure({...})
td.setSignedMode()
td.trackEvent('willbetracked') // will send td_ip and td_client_id; td_global_id will also be sent if set.

Treasure#setAnonymousMode

Prohibit sending of Personally Identifying Information over the wire: td_ip, td_client_id, and td_global_id.

Parameters:

  • keepIdentifier: Boolean (optional) - Keep the cookies

By default setAnonymousMode will remove all cookies that are set by Treasure Data JavaScript SDK, you can set keepIdentifier parameter to true to not remove the cookies.

Example:

var td = new Treasure({...})
td.setAnonymousMode()
td.trackEvent('willbetracked') // will NOT send td_ip and td_client_id; td_global_id will also NOT be sent if set.

Treasure#inSignedMode

Informational method, indicating whether trackEvents method will automatically collect td_ip, td_client_id, and td_global_id if set.

Example:

var td = new Treasure({...})
td.inSignedMode() // false, default
td.trackEvent('willbetracked') // will NOT send td_ip and td_client_id; td_global_id will also NOT be sent if set.
td.setSignedMode()
td.inSignedMode() // true
td.trackEvent('willbetracked') // will send td_ip and td_client_id; td_global_id will also be sent if set.

Treasure#fetchServerCookie(success, error, forceFetch)

This functionality complies with ITP 1.2 tracking. Contact Technical Support or your Customer Success representative to enable this feature.

Parameters:

  • success : Function (optional) - Callback for when sending the event is successful
  • error : Function (optional) - Callback for when sending the event is unsuccessful
  • forceFetch : Boolean (optional) - Forces a refetch of server side id and ignores cached version (default false)

Example:

var td = new Treasure({...})

var successCallback = function (serverSideId) {
  // celebrate();
};

var errorCallback = function (error) {
  // cry();
}

td.fetchServerCookie(successCallback, errorCallback)

Treasure#resetUUID

Parameters:

  • suggestedStorage : Object (optional) - Custom storage configuration
  • suggestedClientId : String (optional) - Custom client id

Reset the client's UUID, set to Treasure Data as td_client_id. You can specify custom storage and custom client id.

See Track/Storage parameters section for more information on storage's configuration

Example:

var td = new Treasure({...})
td.resetUUID() // set td_client_id as random uuid
var td = new Treasure({...})
td.resetUUID(
  {
    name: '_td', // cookie name
    expires: 63072000,
    domain: 'domain',
    customDomain: true/false
    path: '/'
  },
  'xxx-xxx-xxxx' // client id
)

Treasure#trackClicks

Setup an event listener to automatically log clicks. The event will be hooked only follows

  • role=button or role=link
  • <a>
  • <button>
  • <input>). exclude for <input type='password'>

Example:

var td = new Treasure({...})
td.trackClicks({
    element         : '...'
    extendClickData : '...'
    ignoreAttribute : '...'
    tableName       : '...'
    })
  • element: HTMLElement -> Default is window.document. Default setting will observe all elements above. You can set an element if you want to focus on a particular element.
  • extendClickData: Function -> Default is function to set element attributes. You can set function adding special tracking data by extending function(e: event, elementData: ElementObject).
  • ignoreAttribute: string -> Default is "td-ignore" You can set attribute name to ignore element. (e.g. <span role='button' class='button-design' id='button-id' td-ignore />)
  • tableName: string -> Default tableName is "clicks". Click tracking event will be stored into tableName in TreasureData

Treasure#trackPageview(table, success, error)

Helper function that calls trackEvent with an empty record.

Parameters:

  • table : String (required) - table name, must be between 3 and 255 characters and must consist only of lower case letters, numbers, and _ (underscore)
  • success : Function (optional) - Callback for when sending the event is successful
  • error : Function (optional) - Callback for when sending the event is unsuccessful

Example:

var td = new Treasure({...});
td.trackPageview('pageviews');

Treasure#trackEvent(table, record, success, error)

Creates an empty object, applies all tracked information values, and applies record values. Then it calls addRecord with the newly created object.

Parameters:

  • table : String (required) - table name, must be between 3 and 255 characters and must consist only of lower case letters, numbers, and _ (underscore)
  • record : Object (optional) - Additional key-value pairs that get sent with the tracked values. These values overwrite default tracking values
  • success : Function (optional) - Callback for when sending the event is successful
  • error : Function (optional) - Callback for when sending the event is unsuccessful

Example:

var td = new Treasure({...});

td.trackEvent('events');
/* Sends:
{
  "td_ip": "192.168.0.1",
  ...
}
*/

td.trackEvent('events', {td_ip: '0.0.0.0'});
/* Sends:
{
  "td_ip": "0.0.0.0",
  ...
}
*/

Treasure#set()

Default value setter for tables. Set default values for all tables by using $global as the setter's table name.

Treasure#set(table, key, value)

Useful when you want to set a single value.

Parameters:

  • table : String (required) - table name
  • key : String (required) - property name
  • value : String | Number | Object (required) - property value

Example:

var td = new Treasure({...})
td.set('table', 'foo', 'bar');
td.addRecord('table', {baz: 'qux'});
/* Sends:
{
  "foo": "bar",
  "baz": "qux"
}
*/

Treasure#set(table, properties)

Useful when you want to set multiple values.

Parameters:

  • table : String (required) - table name
  • properties : Object (required) - Object with keys and values that you wish applies on the table each time a record is sent

Example:

var td = new Treasure({...})
td.set('table', {foo: 'foo', bar: 'bar'});
td.addRecord('table', {baz: 'baz'});
/* Sends:
{
  "foo": "foo",
  "bar": "bar",
  "baz": "baz"
}
*/

Treasure#get(table)

Takes a table name and returns an object with its default values.

NOTE: This is only available once the library has loaded. Wrap any getter with a Treasure#ready callback to ensure the library is loaded.

Parameters:

  • table : String (required) - table name

Example:

var td = new Treasure({..});
td.set('table', 'foo', 'bar');
td.get('table');
// {foo: 'bar'}

Treasure#ready(fn)

Takes a callback which gets called one the library and DOM have both finished loading.

Parameters:

  • fn : Function (required) - callback function
/* javascript snippet here */
var td = new Treasure({...})
td.set('table', 'foo', 'bar');

td.ready(function(){
  td.get('table');
  // {foo: 'bar'}
});