目录
此内容是否有帮助?

# JavaScript SDK User Guide

TIP

Before accessing, please read the preparation before accessing .

You can get JavaScript SDK source code in GitHub (opens new window).

JavaScript SDK running environment must be a browser, not compatible with IE 8 and below.

The JavaScript SDK is approximately 35 KB in size

**The latest version is **: v1.4.3

**Updated **: 2021-11-19

Download address (opens new window)

# I. Introduction of JavaScript SDK

  1. Download the JavaScript SDK (opens new window)

There are two kinds of standard scripts provided in the compression package. You can choose the script you want according to your needs. The asynchronous loading described below requires the use of thinkingdata.min.jsfiles; synchronous loading requires the use of thinkingdata.umd.min.js.

  1. Load the JavaScript SDK

You can choose to load asynchronously or synchronously using the SDK. The two methods are not very different in actual use, and you can choose one.

When initializing the SDK, you need to pass in some configuration parameters:

  • AppId: The APP_ID of your project, which needs to be configured, will be given when you apply for the project, please fill in here
  • ServerUrl: URL to upload data, need to be configured

    If you are using Cloud as a Service, enter the following URL:

https://receiver.ta.thinkingdata.cn/sync_js

Or http://receiver.ta.thinkingdata.cn/sync_js

If you are using the version of private deployment, enter the following URL:

http://Data Acquisition Address/sync_js

  • send_method: Data reporting method, the default is'image ', that is, using the image GET request method to report data, which can be replaced by'ajax'
  • useAppTrack: Whether to open and open the APP, set when you need to collect H5 page data in the APP, trueis open, the default is false, that is, not open; for details, please see H5 and APP SDK open section.
  • showLog: Whether to print the reported data, after opening, the reported data will be printed in the browser console. The default is true.
  • Persistence: Local cache type, default is localStorage, configurable as cookie.localStoragedoes not support cross-subdomain sharing. If you have similar requirements, please select cookie type.
  • Mode: Run mode, default is normal mode, can be set to debugor debug_only. Please refer to the Debug Mode section

    Note: The above configuration parameters can be configured in both asynchronous loading and synchronous loading. Generally speaking, only appId and serverUrl need to be configured.

# II. Set the User ID

After the initialization of the JS SDK is completed, the SDK will automatically generate a random guest ID as the user ID, which will be used as the user's identity in the unlogged state. If your user has an account ID, please use loginto set the user's account ID. You can also modify the default guest ID through the relevant interface.

# 2.1 Set Visitor ID (optional)

If the user can be used in your product without logging in, and you need to configure the user's visitor ID in the unlogged state, you can call identifyto set it:

ta.identify("123ABCabc");

If you need to get a guest ID, you can call getDistinctIdto get:

//Returns the visitor ID, in case of multiple instances, the visitor ID of the calling instance is returned
var distinctId = ta.getDistinctId();

# 2.2 Set Account ID

When the user generates login behavior, you can use loginto set the user's account ID. The TA platform preferentially uses the account ID as the identity, the set account ID will be saved, and multiple calls to loginwill overwrite the previous account ID:

// Unique logon identification of the user corresponding to #account_in the reported data Id, at this time the value of #account_id is "ABC_123456"
ta.login("ABC_123456");

// Call login again to adjust the account ID, when the value of #account_id is "XYZ_987654"
ta.login("XYZ_987654");

Note that this method does not upload events for user logins**.**

# 2.3 Clear Account ID

After the user produces login behavior, you can call logoutto clear the account ID. Before the next call to login, the guest ID will be used as the identification ID:

// Remove #account_from reported data Id, then the data will not have'#account_id'
ta.logout();

Note that this method does not upload user logged-out events**.**

# III. Send Events

# 3.1 Upload Events

You can directly call trackto upload custom events. It is recommended that you set the attributes of the event and the conditions for sending information according to the previously combed doc. Here, take the purchase of goods as an example:

ta.track(
  "Purchase", //Name of tracking event
  {
    Item: "商品A",
    ItemNum: 1,
    Cost: 100,
    Elements: ["apple", "ball", "cat"],
  } //Event attributes to upload
);
  • The trackinterface has two parameters, the first parameter is the name of the event, and the second parameter is the attribute of the event.
  • The name of the event is string, can only start with a letter, can contain numbers, letters and an underscore '_', is up to 50 characters in length, and is not sensitive to letter case.
  • The attribute of the event is a JSON-formatted object, where the element must be in the form of Key: Value, and each element represents an attribute.
  • Key is the name of the attribute, which is of stringtype. It is stipulated that it can only start with a letter, contain numbers, letters and underscore '_', and is up to 50 characters in length. It is not sensitive to case of letters.
  • Support for String, Number, Boolean, Dateand Array.

    Note: Array type is supported after v1.3.0, and needs to be compatible with TA platform version 2.5 and above.

# 3.2 Monitor HTML Element Click Events

If you want to track click events of elements on a page, you can use trackLinkto batch monitor HTML elements:

ta.trackLink(
  {
    tag: ["a", "button"], //HTML Tag
    class: ["class1", "class2"], //Customize Class name
    id: ["id1", "id2"], //Customize ID Name
  }, //Rules for monitoring elements
  "click", //Name of tracking event
  {
    production: "Product Name",
    name: "Element Identification Name",
  } //Event attributes
);
  • The first parameter is the rule of the elements you need to monitor. The type is a JSON object. It supports tracking the page elements that need to be monitored according to the HTML tag type, Class, and id. You must choose at least one way to select the DOM element. For elements that meet the rules, the click event of the element will be monitored by the event listener. When the listener element is clicked, an event will be reported. The event name and event attribute take the values of the following two parameters.
  • The second parameter is the name of the event, which is of type string. The rule is consistent with the event name of the trackinterface and must be filled in.
  • The third parameter is the attribute of the event, the type is the JSON object, if there is no attribute to be reported, you can pass in an empty JSON.
  • This interface specifies that the event attribute 'name'is the identification of the element. If the event attribute 'name'is not set in parameter three, this interface will obtain the specific attribute value of the monitored element as the element identification according to the following logic. Take the value, the custom attribute of the element 'td-name ', the innerHTMLof the element, the value of the element, and if none of them are taken, pass "No ID obtained".

    This interface will only set the event listener for elements that conform to the rules when they are called. Therefore, after calling the interface, the identification of the element changes or becomes a new element that conforms to the rules. The events reported by the listener will not be changed accordingly. If you need to monitor the newly generated element, you can call this interface after the element is generated in ajax.

# 3.3 Set Common Event Properties

In the process of collecting data, some fields will be shared by multiple events. For example, all events occurring on the same page should have the page attributes of this page, and the user's account information should be included in all data. Then when calling trackto report the event, these.

Properties need to be set once every time. For such properties, you can use the public property setting interface to set them uniformly:

# 3.3.1 Public property types

Before introducing how to set public attributes, you need to understand the characteristics of three types of public attributes, and choose the appropriate type according to actual needs:

  • Page public properties: Effective for the current page, with the highest priority. If the SDK is reinitialized, the page public properties will be emptied. Only fixed values can be set.
  • Dynamic public properties: Effective for the current page, the priority is second to the page public properties. After reinitializing the SDK, you need to set the dynamic public properties again, and you can set dynamic variables.
  • Static public attribute: Effective for all pages. The lowest priority, if caching is turned on, it will be cached in localStorage or cookie. Only a fixed value can be set.

# 3.3.2 Set page public properties

For static properties in some pages, such as the name or address of a page, you may want to add this property to all events triggered in this page. For static properties like this that need to apply to all events in the page, you can use setPagePropertyto set them. Please note that the public property set with setPagePropertyis only valid for the current page

// Set the page ID to a common property of the page with the following attributes for all events triggered on the page
ta.setPageProperty({ page_id: "page10001" });

If you want to get the page public properties of the current page, you can call getPagePropertyto get

// Get the page common attributes for the current page
var pageProperty = ta.getPageProperty();

# 3.3.3 Set the dynamic public properties of the page

In v1.1.0, the feature of dynamic public properties of pages has been added. By setting the callback function of the dynamic public property through setDynamicSuperProperties, the SDK will trigger the callback function when the event is reported and add the returned JSON object to the event property.

The argument to setDynamicSuperPropertiesis a function that returns a JSON object whose format is consistent with the event property.

// Set dynamic common attributes, trigger callback functions when an event is reported, and add the returned JSON object to the event attributes
ta.setDynamicSuperProperties(function () {
  var d = new Date();
  d.setHours(10);
  return { date: d };
});

/*  
ta.setDynamicSuperProperties(
    ()=>{
        var d = new Date();
        d.setHours(10); 
        return {'date': d}
    });
*/

# 3.3.4 Setting static public properties

For some important attributes, such as the user's channel, nickname, ID, etc., these attributes need to be set in each event. You can call setSuperPropertiesto set the static public event attributes, which will take effect globally. When caching is turned on (it is turned on by default), static public properties are cached in localStorageor cookies.

The argument to the static public property is a JSON object whose format is required to be consistent with the event property.

// Set common event attributes with all data events
ta.setSuperProperties({ channel: "Channel name", user_name: "Product name" });

If you need to get all the set static public properties, you can call getSuperProperties; if you need to delete a static public property, you can call unsetSuperPropertyto clear one of the static public properties; if you want to empty all the static public properties, you can call clearSuperProperties; if you want to get all the public event properties, you can call getSuperProperties;

// Get static common event attributes
var superProperties = ta.getSuperProperties();

// Clear a static public event property, such as the'channel'property that was previously set, and the data that follows will not
ta.unsetSuperProperty("channel");

// Clear all static public event attributes
ta.clearSuperProperties();

# 3.4 Record the duration of the event

You can call timeEventto start timing, configure the event type you want to time, when you upload the event, the timing will end, and the SDK will automatically add the #durationattribute to the event attribute of the event to indicate the length of the record, in seconds, timeEventsupports cross-page timing.

// Start the timer and record the event as'Purchase'
ta.timeEvent("Purchase");

// Other codes

// Upload event, time is over,'Purchase'will have the attribute'#duration' indicating the length of the event
ta.track("Purchase", { Item: "商品A", ItemNum: 1, Cost: 100 });

# 3.5 Automatic collection of page browsing events

TA provides an interface to automatically collect page browsing events. You only need to use the following code, and the JS SDK will automatically upload user browsing page events:

ta.quick("autoTrack");

# IV. User Features

# 4.1 Set User Features ( userSet )

For general user features, you can call the userSetto set it. Attributes uploaded using this interface will overwrite the original attribute values. If the user feature does not exist before, the user feature will be created.

// Set user attributes, set membership levels
ta.userSet({ vip_level: "Diamond Members" });

# 4.2 Initializing User Features ( userSetOnce )

If the user feature you want to upload only needs to be set once, you can call userSetOnceto set it. When the attribute already has a value, this information will be ignored.

// For example, set a username and ignore this setting if it is already set. If not, set to the incoming value
ta.userSetOnce({ UserName: "TA" });

# 4.3 Accumulate User Features ( userAdd )

When you want to upload a numeric attribute, you can call userAddto accumulate the attribute. If the attribute has not been set, a value of 0 will be assigned before calculation. If a negative value is passed in, it is equivalent to a subtraction operation.

// For example, if the user calls this interface every time he pays, then'total_ The revenue'field processes the accumulated payment amount each time
ta.userAdd({ total_revenue: 50 });

# 4.4 Reset User Features ( userUnset )

When you want to empty a user feature value of a user, you can call userUnsetto empty the specified property. If the property has not been created in the cluster, the userUnsetwill not create the property.

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

# 4.5 Delete User ( userDel )

If you want to delete a user, you can call userDelto delete the user. You will no longer be able to query the user features of the user, but the events generated by the user can still be queried.

ta.userDel();

# 4.6 Additional Elements to Array Type Data ( userAppend )

Since v1.3.0, you can call userAppendto append elements to user data of type Array (List).

ta.userAppend({ Elements: [("a": 1), ("b": 2)] });

Note: This feature needs to be used with TA Platform 2.5 and later.

# V. Other Functions

# 5.1 Multiple Instances

In v1.1.0, the function of multiple instances is added. You can create child instance objects by calling the initInstancemethod. Its parameter is the name of the child instance. You can then call the interface of the child instance by that name.

// Create an instance with the name newInstance
ta.initInstance("newInstance");

// Set distinct_for the sub-instance ID and send test_ Event
ta.newInstance.identify("new_distinct_id");
ta.newInstance.track("test_event");

By default, the child instance has the same configuration as the main instance ( appId, serverUrl, etc.). And by default, the local cache is not turned on by the child instance.

If you need to configure the parameters for the child instances separately, you can pass in the configuration information during initialization. By passing in different appIdvalues in the configuration information, you can achieve the function of reporting data to different projects:

// Define configuration parameters for sub-instances
var param = {
  appId: "debug-appid",
  serverUrl: "ANOTHER_SERVER_URL",
  persistenceEnabled: true, // Open the local caching of the sub-instance, which is distinguished by the name of the sub-instance
  send_method: "image",
  showLog: true,
};

// Initialize sub-instance
ta.initInstance("anotherInstance", param);

//Report data to master example project
ta.track("Event");

//Report data to sub-example projects
ta.anotherInstance.track("Event");

The ID system of the main instance and the sub-instance is not interoperable, and the public attributes are not interoperable. You can set the user ID for each instance separately. The following cases use this feature to invite friends for the inviters and invitees of this event. Report the success of the invitation and the invited event.

//The main instance is the new user invited and the sub-instance is the inviter
ta.login("invitee");
ta.anotherInstance.login("inviter");

//New user triggers invited event
ta.track("be_invited");

//Inviter triggers an invitation to a new user event
ta.anotherInstance.track("invite_new_user");

# 5.2 Get the Device ID

In v1.1.0, an interface was added to get the device ID (that is, the preset attribute #device_id). You can get the device ID by calling getDeviceId:

var deviceId = ta.getDeviceId();

// If you need to set the device ID to the visitor ID, you can call it as follows
// ta.identify(ta.getDeviceId());

# 5.3 Debug Mode

Since v1.4.0, you can turn on Debug mode by setting the mode parameter in the initialization configuration. Debug mode is only used for data format verification during the development phase, and do not turn on Debug mode in the online environment.

The current SDK instance supports two Debug modes:

  • 'Debug': Report and verify data through the Debug interface
  • 'debug_only': Validation data only, not storage

Since Debug affects cluster performance and data collection stability, it is stipulated that only specified devices can turn on Debug mode. Debug mode can only be enabled on the web side, and the device ID randomly generated by the SDK is configured in the event tracking management related page in the TA.

The device ID can be obtained in the following ways:

  • #device_id attribute in event data in TA platform
  • The #device_id field in the observation report event data in the console log

# 5.4 Pause/stop Data Reporting

In v1.4.2 version, the function of stopping SDK instance reporting data has been added. There are two types of interfaces to stop SDK instance reporting:

# 5.4.1 Pause SDK reporting (enableTracking)

You may want to temporarily stop data collection and reporting in some scenarios, such as when the user is in a test environment or when the user logs in to a test account. At this time, you can call the following interfaces to temporarily stop the reporting of SDK instances.

You can call enableTrackingthrough an instance (including the main instance and the light instance), pass in falseto suspend the reporting of the SDK instance. The #distinct_id, #account_id, public attributes that have been set by the instance will be retained; the data that has been collected but has not been successfully reported by the instance will continue to try to report; the subsequent instance cannot collect and report any new data, cannot set visitor ID, account ID, and public attributes, etc., but can read that the instance has Set the public properties and device ID, guest ID, account ID and other information.

The stop state of the instance will be saved in the local cache until the enableTrackingis called, and trueis passed in. The SDK instance will resume data collection and reporting. It should be noted that the light instance is not cached, so every time you open the App, the paused state of the light instance will not be retained, and the reporting will be reopened.

// Pause reporting
instance.enableTracking(false);

// Restore reporting
instance.enableTracking(true);

# 5.4.2 Stop SDK reporting (optOutTracking)

In some special situations, you may need to completely stop the function of the SDK instance. For example, in areas where GDPR is applicable, the user chooses not to provide data collection permissions, you can call the following interface to completely turn off the function of the SDK instance.

OptOutTrackingcan only be called through the main instance, and the biggest difference with enableTrackingis that it will empty the local cache of this instance, including the guest ID, account ID, public attributes, and unreported data queues of this instance. Then turn off the collection and reporting functions of this instance.

// Stop reporting and reset local caching
instance.optOutTracking();

The stop state of the instance will also be saved in the local cache until the optInTrackingis called, and subsequent reports can continue, but this is equivalent to a completely new instance

// Re-start reporting
instance.optInTracking();

# VI. Relevant Preset Properties

The following preset properties are included with all events in the JavaScript SDK, including AutoCollect events.

Attribute name
Chinese name
Description
#ip
IP address
The user's IP address, which the TA will use to obtain the user's geographic location information
#country
Country
User's country, generated according to IP address
#country_code
Country code
The country code of the country where the user is located (ISO 3166-1 alpha-2, that is, two uppercase English letters), generated based on the IP address
#province
Province
The user's province is generated according to the IP address
#city
City
The user's city is generated according to the IP address
#device_id
Device ID
User's device ID
#screen_height
Screen height
The screen height of the user equipment, such as 1920, etc
#screen_width
Screen width
The screen height of the user equipment, such as 1080, etc
# lib
SDK type
The type of SDK you access, such as JavaScript, etc
#lib_version
SDK version
The version you access to the SDK
#os
Operating system
Such as Android, iOS, etc
#browser
Browser Type
The browser type used by the user, such as Chrome, Firefox, etc
#browser_version
Browser version
Version of the browser used by the user, such as Chrome 61.0, Firefox 57.0, etc
#url
Page address
Address of the current page
#url_path
Page path
The path to the current page
#referrer
Forward address
The address of the page before the jump
#referrer_host
Forward path
The path to the page before the jump
#title
Page Title
Title of the current page
#zone_offset
Time zone offset
The number of hours the data time is offset from UTC time

# 6.1 Get Prefabricated Attributes

When server level event tracking requires some preset properties on the App side, you can obtain the preset properties on the client side through this method and then pass them to the server level.

//Get Attribute Object
var presetProperties = ta.getPresetProperties();

//Generate event preset properties
var properties = presetProperties.toEventPresetProperties();
/*
    {
      "#os":"Mac OS X",
      "#screen_width":1920,
      "#screen_height":1080,
      "#browser":"chrome",
      "#browser_version":"91.0.4472.114",
      "#device_id":"17a3858fafd9b4-0693d07132e2d1-34657600-2073600-17a3858fafea9b",
      "#zone_offset":8
    }
   */

//Get a preset property
var os = presetProperties.os; //os type,as Android
var screenWidth = presetProperties.screenWidth; //Screen width
var screenHeight = presetProperties.screenHeight; //Screen height
var browser = presetProperties.browser; //Browser Type
var browserVersion = presetProperties.browserVersion; //Browser Version Number
var deviceId = presetProperties.deviceId; //Device ID
var zoneOffset = presetProperties.zoneOffset; //Time zone offset value

IP, country city information is generated by server level parsing, and the client side does not provide an interface to obtain these attributes

# VII. Advanced Functions

Starting from v1.4.0, the SDK supports the reporting of three special types of events: first-time events, updatable events, and rewritable events. These three events need to be used in conjunction with TA system 2.8 and later versions. Since special events are only applicable in certain specific scenarios, please use special events to report data with the help of Count Technology's customer success and analysts.

# 7.1 First Incident

First events are events that are recorded only once for a device or another dimension ID. For example, in some scenarios, you may want to record the first event on a browser (judging uniqueness with a #device_id randomly generated by TA SDK), you can use the first event to report the data.

// Instance:Report device first event assuming the event name is DEVICE_FIRST
ta.trackFirstEvent({
  eventName: "DEVICE_FIRST",
  properties: { INT_PROPERTY: 0 },
});

If you want to determine whether it is the first time in a dimension other than the device ID, you can set FIRST_CHECK_ID for the first time event. For example, if you need to record the first event of an account, you can set the account ID to the FIRST_CHECK_ID of the first event:

// Instance:First event to report a user account, assuming the event name is USER_FIRST
// Set the user ID as the first event
ta.trackFirstEvent({
  eventName: "USER_FIRST",
  firstCheckId: "YOUR_ACCOUNT_ID",
  properties: { INT_PROPERTY: 0 },
});

Note: Due to the completion of the verification of whether it is the first time at the server level, the first event will be delayed by 1 hour by default.

# 7.2 Updatable Events

You can implement the need to modify event data in a specific scenario through updatable events. Updatable events need to specify an ID that identifies the event and pass it in when you create an updatable event object. The TA background will determine the data that needs to be updated based on the event name and event ID.

// Instance:Report an event that can be updated, assuming the event name is UPDATABLE_EVENT
ta.trackUpdate({
  eventName: "UPDATABLE_EVENT",
  properties: { status: 3, price: 100 },
  eventId: "test_event_id",
});
// Event attributes after reporting are status 3 and price 100

ta.trackUpdate({
  eventName: "UPDATABLE_EVENT",
  properties: { status: 5 },
  eventId: "test_event_id",
});
// Event attributes status is updated to 5 after reporting, price remains unchanged

# 7.3 Rewritable Events

Rewritable events are similar to updatable events, except that rewritable events will completely cover historical data with the latest data, which is equivalent to deleting the previous data and storing the latest data in effect. The TA background will determine the data that needs to be updated based on the event name and event ID.

// Instance: Report an event that can be overridden, assuming the event name is OVERWRITE_ EVENT
ta.trackOverwrite({
  eventName: "OVERWRITE_EVENT",
  properties: { status: 3, price: 100 },
  eventId: "test_event_id",
});

// Event attributes after reporting are status 3 and price 100
ta.trackOverwrite({
  eventName: "OVERWRITE_EVENT",
  properties: { status: 5 },
  eventId: "test_event_id",
});

// Event attributes status is updated to 5 and price attributes are deleted after reporting

Note: Updatable events and rewritable events will update the event time of historical data by default using the current time of the device. If you want to specify the event time, you can specify the event time when reporting the updatable event

// In the case of trackUpdate, eventTime of Date type can be passed in to specify the event time
ta.trackUpdate({
  eventName: "UPDATABLE_EVENT",
  properties: { status: 5 },
  eventId: "test_event_id",
  eventTime: realEventTime,
});

# Change Log

# 1.4.3 2021/11/19

  • Optimize the function of setting static public properties
  • Code optimization

# 1.4.2 2021/08/23

  • Added enableTracking interface
  • Added optOutTracking interface
  • Added optInTracking interface

# 1.4.1 2021/06/24

  • Support prefabricated attribute acquisition
  • Optimize reporting address processing logic

# 1.4.0 2020/08/25

  • Support for first-time events, allowing custom ID verification to be passed in to check whether it is reported for the first time
  • Supports updatable, rewritable events
  • Support DEBUG mode, verify data format through background

# 1.3.0 2020/02/10

  • Array type support
  • Add userAppend interface
  • Remove local data format validation

# 1.2.0 2019/10/22

  • Added userUnset interface to clear a user feature
  • Added preset property #zone_offset in hours. By default, the offset of the local time zone will be reported to the server level, which will be affected by daylight saving time. The following formula is satisfied:
utc_time + #zone_offset = #event_time

# 1.1.0 2019/07/23

  • Default use localStoragecache #device id, #distinct id, #account idand other data that need persistence
  • Support for multiple instances: In principle, only #device idis shared between multiple instances. All other properties and configurations are not shared and can be reported to different projects separately
  • Add interface:
    • getDeviceId()
    • getDistinctId()
    • getPageProperty()
    • setSuperProperties(superProperties)
    • unsetSuperProperty(propertyName)
    • clearSuperProperties()
    • getSuperProperties()
    • setDynamicSuperProperties(function)
    • timeEvent(eventName)
  • Add attribute legitimacy check logic
  • Automatic collection click event-based optimization:
    • Add #element_typeattribute, pass in nodeName
    • Add page properties, similar to ta_pageview
    • Optimize automatic acquisition logic and fix known bugs
  • The callback function can be passed in by adding loadedparameter to the initialization parameter. This function will be called back when the initialization is completed.
  • Other optimizations:
    • Fix device id not persistent bug
    • Optimize initialization logic
    • The preset attribute adds #os to collect operating system information in ua

# 1.0.7 2019/05/31

  • Fix compatibility bug

# 1.0.6 2019/05/10

  • Support identifierinterface