Use of Treasure Data JavaScript SDK is a powerful way to track customer data from your website. By using the SDK, you don’t have to install anything server-side to track website activities.
Prerequisites
- Basic knowledge of JavaScript and HTML.
- Basic knowledge of Treasure Data.
Setting up website tracking and install the Treasure Data JavaScript SDK
Add the JavaScript SDK to the header of each page you want to track.
For transparency, we’re open sourcing our JavaScript SDK on Github. Check the repository, if necessary. The README contains the full description of JavaScript SDK API. There are some additional APIs to track custom events and such.
- Open the TD Console.
- Locate your Treasure Data write-only API key.
- Add the following code to the header (<head>) of each of the pages that you want to track.
<!-- Treasure Data -->
<script type="text/javascript">
!function(t,e){if(void 0===e[t]){e[t]=function(){e[t].clients.push(this),this._init=[Array.prototype.slice.call(arguments)]},e[t].clients=[];for(var r=function(t){return function(){return this["_"+t]=this["_"+t]||[],this["_"+t].push(Array.prototype.slice.call(arguments)),this}},s=["blockEvents","unblockEvents","setSignedMode","setAnonymousMode","resetUUID","addRecord","fetchGlobalID","set","trackEvent","trackPageview","trackClicks","ready"],n=0;n<s.length;n++){var c=s[n];e[t].prototype[c]=r(c)}var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src=("https:"===document.location.protocol?"https:":"http:")+"//cdn.treasuredata.com/sdk/2.1/td.min.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)}}("Treasure",this);</script>
Initialize and Send Events to the Cloud
You need to create one Treasure client object per database, and initialize pageview tracking by calling the trackPageview() function.
Each event fires off asynchronously.
- Add the following code snippet to include your write-only API key, get a tracker object, and indicate the Treasure Data database where you want to have information from the sites saved to.
<script type="text/javascript">
// Configure an instance for your database
var td = new Treasure({
host: 'in.treasuredata.com',
writeKey: 'YOUR_WRITE_ONLY_APIKEY_IS_HERE',
database: 'DATABASE_NAME'
});
// Enable cross-domain tracking
td.set('$global', 'td_global_id', 'td_global_id');
// Track pageview information to 'pageviews' table
td.trackPageview('pageviews');
</script>
|
IP whitelist are not applied to any import from JavaScript SDK. |
|
Web browsers frequently specify invalid timestamps (such as 1970/01/01). For this reason, logs that have a timestamp older than 7 days, or are 3 days ahead of the current date are ignored. |
By calling the trackPageview() function, the following parameters automatically get logged:
- td_version – td-js-sdk’s version
- td_client_id – client’s uuid (1st party cookie – see Anonymous IDs)
- td_global_id – client’s uuid (3rd party cookie – see Anonymous IDs)
- td_charset – character set
- td_language – browser language
- td_color – screen color depth
- td_screen – screen resolution
- td_viewport – viewport size
- td_title – document title
- td_url – document url
- td_user_agent – browser user agent
- td_platform – browser platform
- td_host – document host
- td_path – document pathname
- td_referrer – document referrer
- td_ip – request IP (added at the server-side)
- td_browser – client browser (added at the server-side)
- td_browser_version – client browser version (added at the server-side)
- td_os – client operating system (added at the server-side)
- td_os_version – client operating system version (added at the server-side)
If you want to set the custom parameters, use the td.set() function.
// track pageview information to 'pageviews' table td.set('pageviews', {foo: 'foo', bar: 'bar'}); td.trackPageview('pageviews');
By default, each imported records was inserted time column at our SDK backend server. If you want to use the client side’s clock, set the time column by td.set.
| Our JavaScript SDK does not parse "td_os", "td_os_version" and "td_browser" for Windows10 and Microsoft Edge browser. The newer User Agent parser library are updated to support this combination, but also introduce performance limitations which we deemed unacceptable. We recommend using the Presto TD_PARSE_AGENT UDF for parsing the raw User Agent string contained in td_user_agent. |
(Optional) Enable Tracking Events by Individual
To comply with data privacy regulations in various domains, and specifically GDPR, the Treasure Data Javascript SDK operates in anonymous mode, which means that it does not collect certain event metadata that is personally identifiable. Specifically, by default the following information is not collected in anonymous mode:
- td_ip - request IP (added at the server-side)
- td_client_id - client's uuid (1st party cookie - see [Anonymous IDs](javascript-sdk-anonymous-ids))
- td_global_id - client's uuid (3rd party cookie - see [Anonymous IDs](javascript-sdk-anonymous-ids))
td_client_id and td_global_id are needed if you want to track individual users and analyze their data within and across user sessions, associate the tracked behavior with a real world individual, and more.
You must review your data collection policy with your company's data privacy officer and legal counsel to determine whether you will collect personal information. If you decide to enable tracking of individuals, we also recommend that you integrate with a consent management system to track individual user opt-ins to tracking. When you have determined the user consent, you can enable signed mode of the JS SDK to capture these attributes with your events:
td.setSignedMode()
The code above could be inserted as is shown in the following example:
<script type="text/javascript">
// Configure an instance for your database
var td = new Treasure({
host: 'in.treasuredata.com',
writeKey: 'YOUR_WRITE_ONLY_APIKEY_IS_HERE',
database: 'DATABASE_NAME'
});
// Enable signed mode
td.setSignedMode()
// Enable cross-domain tracking
td.set('$global', 'td_global_id', 'td_global_id');
// Track pageview information to 'pageviews' table
td.trackPageview('pageviews');
</script>
Track Custom Events
You can also track your custom events in addition to page views by using trackEvent() function. In the following example, button is the name of table where events get logged. You can pass additional information/context to the event as an argument.
var buttonEvent2 = function () { td.trackEvent('button', { number: 1 }); // doButtonEvent(1); };
Integrations
JavaScript SDKs are often used with other systems such as:
- Website Tracking with Google Tag Manager (GTM)
- Website Tracking with Google Accelerated Mobile Pages (AMP)
- Website Tracking with Marketo Forms
Appendix: Video
This video demonstrates the steps for website tracking in 3 minutes, but uses the much older versions of TD.
Appendix: API Endpoint
JavaScript SDK uses our REST API endpoint to import the data and it might take a few minutes to reflect the import in the database because of server-side buffering.
# Single Record
$ curl -X POST
-H 'Content-Type: application/json'
-H 'X-TD-Write-Key: your_write_apikey' \
--data-binary '{"name":"komamitsu", "num":1234}' \
https://in.treasuredata.com/js/v3/event/your_db/your_table
# Multiple Records
$ curl -X POST
-H 'Content-Type: application/json'
-H 'X-TD-Write-Key: your_write_apikey' \
-H 'X-TD-Data-Type: k'
--data-binary '{"your_db.your_table":[{"time":1403147720, "name":"komamitsu", "age":41},{"time":1403147721, "name":"kzk", "age":29}]}' \
https://in.treasuredata.com/js/v3/event
| "X-TD-Data-Type: k", Event collector handles several data types. ‘k’ is one of them. It can handle multiple records. |
| When you try the preceding example, change the time value to the current unix time value. Currently timestamps that are older than 7 days, or are 3 days ahead of the current date are ignored. |
Appendix: API Reference
For transparency, we’re open sourcing our JavaScript SDK on Github. Check the repository, if necessary. The README contains the full description of JavaScript SDK API. There are some additional APIs to track custom events and such.
Comments
0 comments
Please sign in to leave a comment.