Skip to main content

Advanced guide

Last updated 10/05/2026

1. Set user IDs​

By default, the SDK instance uses a random number as each user's distinct ID, which serves as the user's identifier while the user is not logged in. Note that the distinct ID changes when the user clears the cache or switches devices.

1.1 Set the distinct ID​

tip

In general, you don't need to customize the distinct ID. Make sure you understand the user identification rules before you set a distinct ID.

ta.setDistinctId("Thinker");

To get the distinct ID, you can call getDistinctId:

//Return the distinct ID
var distinctId = ta.getDistinctId();

1.2 Set the account ID​

When a user logs in, you can call login to set the user's account ID. The AE platform uses the account ID as the identifier, and the account ID you set is kept until logout is called. Calling login multiple times overwrites the previous account ID.

// The unique login ID of the user, which corresponds to #account_id in the reported data. #account_id is now TA
ta.login("TA");

This method does not upload a login event

1.3 Clear the account ID​

After a user logs out, you can call logout to clear the account ID. Until login is called again, the distinct ID is used as the identifier.

ta.logout();

We recommend that you call logout when the user logs out, for example, only when the user signs out of their account, rather than when the app is closed.

This method does not upload a logout event

2. Track events​

After the SDK is initialized, you can start tracking data to collect user behavior. In most cases, regular events meet business needs. You can also use first events, updatable events, and other event types based on your actual business scenarios.

2.1 Regular events​

You can call track to upload events. We recommend setting event properties and the conditions for sending events according to the document you prepared earlier. The following example tracks a user purchasing a product:

ta.track(
"product_buy", //Event name
{ product_name: "Product"} //Event properties
);

2.2 First events​

A first event is an event that is recorded only once for a given device or an ID of another dimension. For example, in some scenarios you may want to record the activation event on a device; you can report this data as a first event

ta.trackFirst({
eventName: "device_activation",
properties: { key:"value" }
});

If you want to determine whether an event is the first one based on a dimension other than the device, you can customize first_check_id for the first event:

// Set the user ID as the FIRST_CHECK_ID of the first event to collect the user's first activation event
ta.trackFirst({
eventName: "account_activation",
firstCheckId: "TA",
properties: { key: "value"}
});

Note: Because the first-event check is performed on the server, first events are stored with a 1-hour delay by default.

2.3 Updatable events​

You can use updatable events to modify event data in specific scenarios. An updatable event requires an ID that identifies the event, which you pass in when you create the updatable event object. The AE backend determines which data to update based on the event name and event ID.

// Example: Report an updatable event. Assume the event name is UPDATABLE_EVENT
// After reporting, the event property status is 3 and price is 100
ta.trackUpdate({
eventName: "UPDATABLE_EVENT",
properties: { status: 3, price: 100 },
eventId: "test_event_id"
});

// After reporting, the event property status is updated to 5, and price stays the same
ta.trackUpdate({
eventName: "UPDATABLE_EVENT",
properties: { status: 5 },
eventId: "test_event_id"
});

2.4 Overwritable events​

Overwritable events are similar to updatable events, except that an overwritable event completely overwrites historical data with the latest data. In effect, the previous record is deleted and the latest data is ingested. The AE backend determines which data to update based on the event name and event ID.

// Example: Report an overwritable event. Assume the event name is OVERWRITE_EVENT
// After reporting, the event property status is 3 and price is 100
ta.trackOverwrite({
eventName: "OVERWRITE_EVENT",
properties: { status: 3, price: 100 },
eventId: "test_event_id"
});


// After reporting, the event property status is updated to 5, and the price property is deleted
ta.trackOverwrite({
eventName: "OVERWRITE_EVENT",
properties: { status: 5 },
eventId: "test_event_id"
});

2.5 Set super properties​

During data collection, some fields are shared by multiple events. For example, all events that occur on the same page should carry the properties of that page, and the user's account information should be carried in all data. Otherwise, you would have to set these properties every time you call track to report an event. For such properties, you can use the super property APIs to set them in one place.

Before you learn how to set super properties, you need to understand the characteristics of the three types of super properties, and then choose the type that suits your needs:

  • Static super properties: Take effect on all pages and have the lowest priority. When caching is enabled, they are cached in localStorage or cookies. Only fixed values can be set.
  • Page super properties: Take effect on the current page and have the highest priority. If the SDK is reinitialized, page super properties are cleared. Only fixed values can be set.
  • Dynamic super properties: Their priority is lower than that of page super properties. After the SDK is reinitialized, you need to set dynamic super properties again. Dynamic variables can be set.

2.5.1 Set static super properties​

Some important properties, such as the user's channel, nickname, and ID, need to be set in every event. You can call setSuperProperties to set static super properties, which take effect globally. When caching is enabled (it is enabled by default), static super properties are cached in localStorage or cookie.

The parameter of static super properties is a JSON object, and its format requirements are the same as those of event properties.

// Set super event properties. All events carry these properties
ta.setSuperProperties({ channel: "Channel name", user_name: "User name" });

In addition to setting properties, we also provide other APIs for working with static super properties to meet day-to-day business needs.

// Get static super event properties
var superProperties = ta.getSuperProperties();
// Clear a static super event property. For example, after the previously set 'channel' property is cleared, subsequent data won't carry this property
ta.unsetSuperProperty("channel");
// Clear all static super event properties
ta.clearSuperProperties();

2.5.2 Set page super properties​

For some static properties of a page, such as the page name or URL, you may want to add the property to all events triggered on that page. For static properties like these that apply to all events on a page, you can use setPageProperty. Note that super properties set with setPageProperty are valid only for the current page

// Set the page ID as a page super property. All events triggered on this page carry the following property
ta.setPageProperty({ page_id: "page10001" });

To get the page super properties of the current page, you can call getPageProperty

// Get the page super properties of the current page
var pageProperty = ta.getPageProperty();

2.5.3 Set dynamic page super properties​

Use setDynamicSuperProperties to set the callback function for dynamic super properties. The SDK triggers the callback function when an event is reported and adds the returned JSON object to the event properties. The parameter of setDynamicSuperProperties is a function, and the function must return a JSON object.

// Set dynamic super properties. The callback function is triggered when an event is reported, and the returned JSON object is added to the event properties
ta.setDynamicSuperProperties(function() {
var d = new Date();
d.setHours(10);
return { date: d };
});

2.6 Track event duration​

To record how long an event lasts, call timeEvent to start timing. Specify the name of the event you want to time; when you upload that event, the #duration property is automatically added to its event properties to indicate the recorded duration in seconds. Note that only one timing task can run for the same event name at a time.

//The following example measures how long a user stays on a product page
ta.timeEvent("stay_shop");
/**do someting
.......
**/
//The user leaves the product page and timing ends. The "stay_shop" event will carry the #duration property that indicates the event duration
ta.track("stay_shop",{product_name:"Product Name"});

2.7 Batch sending​

Batch sending of data requires SDK 1.6.1 or later

var config = {
appId: '2f2d8810817c4cbfb7c38aeb8466615a',
serverUrl: 'https://receiver-ta-preview.thinkingdata.cn',
send_method: 'ajax',
//Enable batch sending. Default: false
batch:true
//or
batch: {
size: 6,//Reporting is triggered automatically when the number of records reaches size. Default: 6
interval: 6000,//Interval in milliseconds after which data is sent immediately. Default: 6s
maxLimit:500//Maximum number of records cached locally. Default: 500
},
};
  • batch: Whether to enable batch sending of data. Optional. Defaults to false
  • size: Reporting is triggered automatically when the number of records reaches size. Defaults to 6. The minimum is 1 and the maximum is 30
  • interval: Sending interval. Defaults to 6000
  • maxLimit: Maximum number of records cached locally. Defaults to 500

Note:

  1. Batch sending and callback functions can't be used at the same time. For example, if you add a callback to track, the callback isn't executed when batch sending is used.
  2. Batch sending sends data through ajax by default.
  3. When the number of records cached in localStorage exceeds maxLimit (500 by default), the oldest data is discarded on a first-in, first-out basis.
  4. You can use only one of app_js_bridge and batch_send. Once bridging is enabled, batch sending can't be used.
  5. Data is stored in localStorage.
  6. In debug or debugOnly mode, data is sent directly instead of being cached locally and reported in batches.
  7. Once enabled, data is reported only when the specified number of records or the specified time interval is reached. Pages that redirect frequently may close before the data is reported, which causes some data loss. Enable this feature with caution.

3. User properties​

The user property APIs supported by the AE platform are userSet, userSetOnce, userAdd, userUnset, userDelete, userAppend, and userUniqAppend.

3.1 userSet​

For general user properties, you can call userSet to set them. Properties uploaded through this API overwrite the existing property values. If the user property does not exist yet, it is created with the same type as the value passed in. The following example sets the user name:

// username is now TA
ta.userSet({ username: "TA" });
//username is now AE
ta.userSet({ username: "AE" });

3.2 userSetOnce​

If a user property only needs to be set once, you can call userSetOnce to set it. If the property already has a value, this call is ignored. The following example sets the first payment time:

//first_payment_time is 2018-01-01 01:23:45.678
ta.userSetOnce({first_payment_time: "2018-01-01 01:23:45.678" });
//first_payment_time is still 2018-01-01 01:23:45.678
ta.userSetOnce({first_payment_time: "2018-12-31 01:23:45.678" });

3.3 userAdd​

When you upload a numeric property, you can call userAdd to accumulate its value. If the property has not been set yet, it is assigned 0 before the calculation. Passing a negative value is equivalent to subtraction.

//total_revenue is now 30
ta.userAdd({ total_revenue: 30 });
//total_revenue is now 678
ta.userAdd({ total_revenue: 648 });

3.4 userUnset​

When you need to clear a user's property value, you can call userUnset to clear the specified property. If the property has not been created in the cluster yet, userUnset does not create it

// Clear the value of the user property named userPropertykey, that is, set it to NULL
ta.userUnset("userPropertykey");

3.5 userDelete​

To delete a user, you can call userDelete. After that, you can no longer query this user's user properties, but the events generated by the user can still be queried.

ta.userDelete();

3.6 userAppend​

You can call userAppend to append elements to user data of the array type.

ta.userAppend({ user_list: ["apple", "ball"] });

3.7 userUniqAppend​

Starting from v1.6.0, you can call userUniqAppend to append unique elements to Array (List) user data. Calling userUniqAppend deduplicates the appended user property values, whereas the userAppend API doesn't deduplicate, so the user property may contain duplicates.

//The value of user_list is now ["apple","ball"]
ta.userAppend({ user_list: ["apple", "ball"] });
//The value of user_list is now ["apple","apple","ball","cube"]
ta.userAppend({ user_list: ["apple", "cube"] });
//The value of user_list is now ["apple","ball","cube"]
ta.userUniqAppend({ user_list: ["apple", "cube"] });

4. Data transmission encryption​

Starting from v1.6.0, data transmission encryption is supported when data is reported through ajax. You can configure encryption settings in the config used to initialize the SDK.

var config = {
appId: "xxx",
serverUrl: "xxx",
secretKey: {
//Public key for encryption, which you can get in the AE management backend
publicKey: 'public key',
//Public key version number
version: 1
},
};

To support data encryption, you also need to import crypto-js and jsencrypt

<script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/crypto-js.js"></script>
<script src="https://cdn.bootcss.com/jsencrypt/3.2.1/jsencrypt.js"></script>

5. Cross-domain tracking​

Cross-domain tracking requires SDK 1.6.1 or later. It unifies user behavior on websites with two different domains, so you can observe the conversion journey of users across related websites more effectively.

ta.quick('siteLinker', {
linker: [
{ part_url: 'thinkingdata.cn', after_hash: true },
{ part_url: 'example.com', after_hash: true }
]
})

part_url: The configured part_url string must be a substring of the URL of the website to be linked.

Domain to linkSettinghref of the a tagLinking result of the a tag
thinkingdata.cn{ part_url: 'thinkingdata.cn', after_hash: false }https://thinkingdata.cn/https://thinkingdata.cn/?_tasdk='d'+distinctID

after_hash: Required. The value must be a Boolean, that is, true or false. It specifies whether the _tasdk parameter is placed in the hash part of the URL (the part after #) or in the search part of the URL (the ? part before #)

urlafter_hashResult

https://thinkingdata.cn

falsehttps://thinkingdata.cn?_tasdk=distinctID
truehttps://thinkingdata.cn#?_tasdk=distinctID
https://thinkingdata.cn#indexfalsehttps://thinkingdata.cn?_tasdk=distinctID#index
truehttps://thinkingdata.cn#index?_tasdk=distinctID

https://thinkingdata.cn?a=1#index

falsehttps://thinkingdata.cn?a=1&_tasdk=distinctID#index
truehttps://thinkingdata.cn?a=1#index?_tasdk=distinctID
https://thinkingdata.cn?a=1#index?b=2falsehttps://thinkingdata.cn?a=1&_tasdk=distinctID#index?b=2
truehttps://thinkingdata.cn?a=1#index?b=2&_tasdk=distinctID

6. Other features​

6.1 Get the device ID​

You can call getDeviceId to get the device ID:

var deviceId = ta.getDeviceId();

6.2 Set the default time zone​

By default, the SDK reports the local time at which the API is called as the event time. You can also set a default time zone during initialization so that the time of all events is aligned to the time zone you set:

var config = {
appId: "xxx",
serverUrl: "xxx",
zoneOffset:8
};

Note: Aligning the event time to a specified time zone discards the device's local time zone information. To keep the device's local time zone information, you currently need to add the relevant properties to events yourself.

6.3 Disable configuration fetching by the SDK​

If you don't want the SDK to fetch configuration during initialization, you can control it as follows:

var config = {
appId: "xxx",
serverUrl: "xxx",
disableRConfig:true
};
ta.init(config);

If disableRConfig is true, configuration fetching is disabled. If it is false, configuration fetching is enabled

Was this page helpful?