Treasure Data JavaScript SDK

This article will help you start sending the data from website to Treasure Data, using our JavaScript SDK library. This way, you don’t have to install anything server-side to track website activities.

Table of Contents

Prerequisites

  • Basic knowledge of JavaScript / HTML.
  • Basic knowledge of Treasure Data.

How to install JavaScript SDK?

This video demonstrates how to install JavaScript SDK in 3 minutes.

Step 1: Install the Library

Install the td-js-sdk on your page by copying-pasting the JavaScript snippet below into your page’s <head> tag:

<!-- 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=["addRecord","set","trackEvent","trackPageview","trackClicks","ready"],a=0;a<s.length;a++){var c=s[a];e[t].prototype[c]=r(c)}var n=document.createElement("script");n.type="text/javascript",n.async=!0,n.src=("https:"===document.location.protocol?"https:":"http:")+"//cdn.treasuredata.com/sdk/1.7.1/td.min.js";var i=document.getElementsByTagName("script")[0];i.parentNode.insertBefore(n,i)}}("Treasure",this);
</script>

Step 2: Initialize & Send Events to the Cloud

You need to create one Treasure client object per database, and initialize pageview tracking by calling the trackPageview() function. The APIKEY can be retrieved from the Console’s profile page. It’s recommended to use write-only API key for SDKs. Each event will fire off asynchronously.

<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');
  // Enable click tracking
  td.trackClicks();
  // Track pageview information to 'pageviews' table
  td.trackPageview('pageviews');
</script>
Untitled-3
IP whitelist won't be applied to any import from JavaScript SDK. We have also seen a lot of cases where browsers specify invalid timestamps (like 1970/01/01), so we're currently ignoring records which have a timestamp older than 7 days, and newer than 3 days ahead.

By calling trackPageview() function, these parameters will automatically gets logged.

  • td_version – td-js-sdk’s version
  • td_client_id – client’s uuid
  • 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 agnet
  • td_platform – browser platform
  • td_host – document host
  • td_path – document pathname
  • td_referrer – document referrer
  • td_ip – request IP (server)
  • td_browser – client browser (server)
  • td_browser_version – client browser version (server)
  • td_os – client operating system (server)
  • td_os_version – client operating system version (server)

If you want to set the custom parameters, please use td.set() function.

// track pageview information to 'pageviews' table
td.set('pageviews', {foo: 'foo', bar: 'bar'});
td.trackPageview('pageviews');

Step 3: Track Custom Events

You can also track your custom events in addition to page views by using trackEvent() function. In the example below, button will be 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);
};

Supported Browsers

These browsers are supported for our JavaScript SDK (the newest version).

Untitled-3
v1.5.2 or later, td-js-sdk dropped support for IE6,7.

Appendix: Google Tag Manager

If you want to use TD JS SDK with Google Tag Manager, please check this article.

Appendix: API Endpoint

JavaScript SDK is hitting our REST API endpoint to import the data. Note that this will take 1 minutes to reflect in the database because of the 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}' \
    http://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}]}' \
    http://in.treasuredata.com/js/v3/event
Untitled-3
"X-TD-Data-Type: k", Event collector handles several data types. ‘k’ is one of them. It can handle multiple records.
Untitled-3
When you try the above example, please change time value to current unixtime value, we're currently ignoring records which have a timestamp older than 7 days, and newer than 3 days ahead.

Next Steps

For transparency, we’re open sourcing our JavaScript SDK on Github. Please check the repository if necessary. The README contains the full description of JavaScript SDK API. There’re some additional APIs to track custom events etc.

Tips

Enable Cross-Domain Tracking

Details of our cross-domain tracking is described in a different article.

Opt-Out Cross Domain Tracking with 3rd Party Cookie ID

In special circumstances where you don’t want to enable cross domain tracking via 3rd party cookie ID, please comment out the following line to opt-out its usage.

// Disable cross-domain tracking
// td.set('$global', 'td_global_id', 'td_global_id');

User Agents for Google Crawlers

td_browser is recognized by user-agents, and it works on our SDK Backend server. td_browser shows the following value for each Google Crawler.(See Google Crawler)

Crawler user-agents HTTP(S) requests user-agent td_browser
Googlebot (Google Web search) Googlebot Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) “Googlebot”
Googlebot (Google Web search) Googlebot (rarely used): Googlebot/2.1 (+http://www.google.com/bot.html) “Googlebot”
Googlebot News Googlebot-News (Googlebot) Googlebot-News “Other”
Googlebot Images Googlebot-Image (Googlebot) Googlebot-Image/1.0 “Other”
Googlebot Video Googlebot-Video (Googlebot) Googlebot-Video/1.0 “Other”
Google Mobile (feature phone) Googlebot-Mobile SAMSUNG-SGH-E250/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 UP.Browser/6.2.3.3.c.1.101 (GUI) MMP/2.0 (compatible; Googlebot-Mobile/2.1; +http://www.google.com/bot.html) “UP.Browser”
Google Mobile (feature phone) Googlebot-Mobile DoCoMo/2.0 N905i(c100;TB;W24H16) (compatible; Googlebot-Mobile/2.1; +http://www.google.com/bot.html) “Other”
Google Smartphone Googlebot Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12F70 Safari/600.1.4 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) “Googlebot”
Google Mobile AdSense Mediapartners-Google [various mobile device types] (compatible; Mediapartners-Google/2.1; +http://www.google.com/bot.html) “Other”
Google Mobile AdSense Mediapartners (Googlebot) [various mobile device types] (compatible; Mediapartners-Google/2.1; +http://www.google.com/bot.html) “Other”
Google AdSense Mediapartners-Google Mediapartners-Google “Other”
Google AdSense Mediapartners (Googlebot) Mediapartners-Google “Other”
Google AdsBot landing page quality check AdsBot-Google AdsBot-Google (+http://www.google.com/adsbot.html) “Other”

Last modified: Nov 28 2016 21:51:08 UTC

If this article is incorrect or outdated, or omits critical information, please let us know. For all other issues, please see our support channels.