{"id":27627208,"url":"https://github.com/treasure-data/td-js-sdk","last_synced_at":"2025-04-23T13:53:35.302Z","repository":{"id":17977135,"uuid":"20978591","full_name":"treasure-data/td-js-sdk","owner":"treasure-data","description":"JavaScript SDK for Treasure Data","archived":false,"fork":false,"pushed_at":"2025-03-26T02:27:47.000Z","size":6887,"stargazers_count":71,"open_issues_count":9,"forks_count":26,"subscribers_count":89,"default_branch":"master","last_synced_at":"2025-03-26T03:27:18.275Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://docs.treasuredata.com/articles/javascript-sdk","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/treasure-data.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-06-18T21:25:17.000Z","updated_at":"2025-03-26T02:27:51.000Z","dependencies_parsed_at":"2023-01-14T12:50:29.196Z","dependency_job_id":"0c9340a1-3c0e-427d-8ffe-141bcc06108c","html_url":"https://github.com/treasure-data/td-js-sdk","commit_stats":{"total_commits":756,"total_committers":36,"mean_commits":21.0,"dds":0.5185185185185186,"last_synced_commit":"b26ccb9059a536e797860cbf8e3d5e16245d74f7"},"previous_names":[],"tags_count":47,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/treasure-data%2Ftd-js-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/treasure-data%2Ftd-js-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/treasure-data%2Ftd-js-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/treasure-data%2Ftd-js-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/treasure-data","download_url":"https://codeload.github.com/treasure-data/td-js-sdk/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250444211,"owners_count":21431605,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-04-23T13:53:34.549Z","updated_at":"2025-04-23T13:53:35.291Z","avatar_url":"https://github.com/treasure-data.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# td-js-sdk\n\n[![CircleCI](https://dl.circleci.com/status-badge/img/gh/treasure-data/td-js-sdk/tree/master.svg?style=svg\u0026circle-token=6fcc04c8184f1b266519f0d0f8901b043af421db)](https://dl.circleci.com/status-badge/redirect/gh/treasure-data/td-js-sdk/tree/master)\n\n\u003e :warning: NOTE: From the version 4.0, we will use our new JavaScript endpoint to log data. This new behavior requires configuration changes, see [Streaming Ingestion](STREAMING_INGESTION.md) for more information.\n\n# Table of Contents\n[Getting started](#getting-started)\n\n[Tracking](#tracking)\n\n[Data privacy](#data-privacy)\n\n[SameSite Cookies](#samesite-cookies)\n\n[Consent Management](CONSENTMANAGER.md)\n\n[Streaming Ingestion](STREAMING_INGESTION.md)\n\n[Collecting third-party tags](COLLECTING_TAGS.md)\n\n[API](#api)\n\n[Others](#support)\n\n---\n\n\n## Build\n\nThe build script (`bin/build.sh`) can be used to configure several aspects of the SDK:\n\n### GLOBAL\nThe global export that the SDK is exported on.  This is kept consistent between the full source and the loader's stub.\n```sh\n\u003e bin/build.sh --GLOBAL=AlternateSDK\n```\n```js\nvar sdk = new AlternateSDK()\n```\n\n### FILENAME\nThe filename to be output, in both full and minified code. This is largely a convenience, and defaults to `td`\n```sh\n\u003e bin/build.sh --FILENAME=foo\n...\n\u003e ls dist/\nfoo.js      foo.min.js      loader.min.js\n```\n\n### URL\nThe URL of the hosted file. This will be defaulted to the URL for the Treasure Data CDN-hosted file.\n```sh\n\u003e bin/build.sh --URL=//cdn.yourdomain.com/sdk/foo.min.js\n```\n\n## Installing\n\n### Script snippet\n\nInstall td-js-sdk on your page by copying the appropriate JavaScript snippet below and pasting it into your page's `\u003chead\u003e` tag:\n\n```html\n\u003cscript type=\"text/javascript\"\u003e\n!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=[\"collectTags\",\"addRecord\",\"blockEvents\",\"fetchServerCookie\",\"fetchGlobalID\",\"fetchUserSegments\",\"resetUUID\",\"ready\",\"setSignedMode\",\"setAnonymousMode\",\"set\",\"trackEvent\",\"trackPageview\",\"trackClicks\",\"unblockEvents\"],c=0;c\u003cs.length;c++){var o=s[c];e[t].prototype[o]=r(o)}var n=document.createElement(\"script\");n.type=\"text/javascript\",n.async=!0,n.src=(\"https:\"===document.location.protocol?\"https:\":\"http:\")+\"//cdn.treasuredata.com/sdk/4.2/td.min.js\";var i=document.getElementsByTagName(\"script\")[0];i.parentNode.insertBefore(n,i)}}(\"Treasure\",this);\n\u003c/script\u003e\n```\n\n### npm\n\nDoes not work with NodeJS. **Browser only**.\n\n```sh\nnpm install --save td-js-sdk\n```\n\nExports Treasure class using CommonJS. The entry point is `lib/treasure.js`. Usable with a build tool such as Browserify or Webpack.\n\n```javascript\nvar Treasure = require('td-js-sdk')\n```\n\n## Getting started\n\n### Get your write-only API key\n\nLog in to [Treasure Data](https://console.treasuredata.com/) and go to your [profile](https://console.treasuredata.com/users/current). The API key should show up right next to your full-access key.\n\n### Initializing\n\n\u003e :warning: NOTE: From the version 4.0, we will use our new JavaScript endpoint to log data. This new behavior requires configuration changes, see [Streaming Ingestion](STREAMING_INGESTION.md) for more information.\n\nOur library works by creating an instance per database, and sending data into tables.\n\nFirst install the library using any of the ways provided above.\n\nAfter installing, initializing it is as simple as:\n\n```javascript\n  var foo = new Treasure({\n    database: 'foo',\n    writeKey: 'your_write_only_key'\n  });\n```\n\nIf you're an administrator, databases will automatically be created for you. Otherwise you'll need to ask an administrator to create the database and grant you `import only` or `full access` on it, otherwise you will be unable to send events.\n\n### Sending your first event\n\n```javascript\n// Configure an instance for your database\nvar company = new Treasure({...});\n\n// Create a data object with the properties you want to send\nvar sale = {\n  itemId: 101,\n  saleId: 10,\n  userId: 1\n};\n\n// Send it to the 'sales' table\ncompany.addRecord('sales', sale);\n```\n\nSend as many events as you like. Each event will fire off asynchronously.\n\n\n## Tracking\n\ntd-js-sdk provides a way to track page impressions and events, as well as client information.\n\n### Client ID and Storage\n\nEach client requires a uuid. It may be set explicitly by setting `clientId` on the configuration object. Otherwise we search the cookies for a previously set uuid. If unable to find one, a uuid will be generated.\n\nA cookie is set in order to track the client across sessions.\n\n### Page impressions\n\nTracking page impressions is as easy as:\n\n```javascript\n/* insert javascript snippet */\nvar td = new Treasure({...});\ntd.trackPageview('pageviews');\n```\n\nThis will send all the tracked information to the pageviews table.\n\n### Event tracking\n\nIn addition to tracking pageviews, you can track events. The syntax is similar to `addRecord`, with the difference being that `trackEvent` will include all the tracked information.\n\n```javascript\nvar td = new Treasure({});\n\nvar buttonEvent1 = function () {\n  td.trackEvent('button', {\n    number: 1\n  });\n\n  // doButtonEvent(1);\n};\n\nvar buttonEvent2 = function () {\n  td.trackEvent('button', {\n    number: 2\n  });\n\n  // doButtonEvent(2);\n};\n```\n\n### Tracked information\n\nEvery time a track functions is called, the following information is sent:\n\n* **td_version** - td-js-sdk's version\n* **td_client_id** - client's uuid*\n* **td_charset** - character set\n* **td_description** - description meta tag\n* **td_language** - browser language\n* **td_color** - screen color depth\n* **td_screen** - screen resolution\n* **td_viewport** - viewport size\n* **td_title** - document title\n* **td_url** - document url\n* **td_user_agent** - browser user agent\n* **td_platform** - browser platform\n* **td_host** - document host\n* **td_path** - document pathname\n* **td_referrer** - document referrer\n\nThe following information will be populated by server-side\n\n* **td_ip** - request IP (server)*. This information is only populated when `td_global_id` is enabled using `td.set('$global', 'td_global_id', 'td_global_id')` and is in signed mode.\n\nAll server values except `td_ip` are found by parsing the user-agent string. This is done server-side to ensure that it can be kept up to date.\n\n\u003cnowiki\u003e*\u003c/nowiki\u003e This is a personally identifiable column, and will be affected by whether or not the user is in Signed or Anonymous Mode.\n\n\n## Default values\n\nSet default values on a table by using `Treasure#set`. Set default values on *all* tables by passing `$global` as the table name.\n\nUsing `Treasure#get` you can view all global properties by passing the table name `$global`.\n\nWhen a record is sent, an empty record object is created and properties are applied to it in the following order:\n\n1. `$global` properties are applied to `record` object\n2. Table properties are applied to `record` object, overwriting `$global` properties\n3. Record properties passed to `addRecord` function are applied to `record` object, overwriting table properties\n\n## Data Privacy\n\nTreasure Data's SDK enables compliance with many common requirements of the EU's GDPR laws. Several methods have been enabled to help you comply with newer and more stringent data privacy policies:\n\n* `blockEvents` / `unblockEvents` - non-argument methods to shut down or re-enable all sending of events to Treasure Data. No messages will be sent, no calls will be cached. Default is for events to be unblocked. See documentation around these methods: [`blockEvents`](#treasureblockevents), [`unblockEvents`](#treasureunblockevents), [`areEventsBlocked`](#treasureareeventsblocked)\n* `setSignedMode` - non-argument method to enter \"Signed Mode\", where some PII may be collected automatically by the SDK. The data sent to Treasure Data will include `td_ip`, `td_client_id`, and `td_global_id`, if specified. See documentation around this method: [`setSignedMode`](#treasuresetsignedmode)\n* `setAnonymousMode` - non-argument method to enter \"Anonymous Mode\", where PII will not be collected automatically by the SDK.  These data will specifically omit `td_ip`, `td_client_id`, and `td_global_id`, if specified.  This is the default behavior.  See documentation around this method: [`setAnonymousMode`](#treasuresetanonymousmode)\n* `resetUUID` - method to reset the `td_client_id` value.  This will overwrite the original value stored on the user's cookie, and will likely appear in your data as a brand-new user.  It's possible to specify a client ID while resetting, as well as custom expiration times by passing in appropriate values.  See documentation around this method: [`resetUUID`](#treasureresetuuid)\n\nA new configuration property has also been added: `config.startInSignedMode`.  This configuration option tells the SDK that, if no express decision has been made on whether the user wants to be in Signed or Anonymous modes, it should default into Signed Mode. The default behavior is to default the user into Anonymous Mode.\n\n### Examples\nSuppose a user first accesses your site, and you need to know if they have agreed to tracking for marketing purposes.  You contract with a Consent Management Vendor to maintain this information, and want to set appropriate values once you know their consent information.\n```js\nvar foo = new Treasure({\n  database: 'foo',\n  writeKey: 'your_write_only_key'\n});\ntd.trackClicks()\n\nvar successConsentCallback = function (consented) {\n  if (consented) {\n    td.setSignedMode()\n  } else {\n    td.setAnonymousMode()\n  }\n}\n\nvar failureConsentCallback = function () {\n  // error occurred, consent unknown\n  td.setAnonymousMode()\n}\n\nConsentManagementVendor.getConsent(userId, successConsentCallback, failureConsentCallback)\n```\n\nIn this scenario, the Consent Management Vendor returns a true or false value in the callback based on whether or not the user associated with the `userId` has consented to their PII being used for marketing purposes.  Non-PII data may still be collected.\n\nNow suppose your Consent Management Vendor provides strings based on the consent level: `MARKETING`, `NON-MARKETING`, `REFUSED`, for \"Consented to PII being used for marketing purposes\", \"Consented to data being collected for non-marketing purposes\", and \"Refused all data collection\".  There's only a minor change to make in the `successConsentCallback`:\n\n```js\nvar successConsentCallback = function (consented) {\n  if (consented === 'MARKETING') {\n    td.unblockEvents()\n    td.setSignedMode()\n  } else if (consented === 'NON-MARKETING') {\n    td.unblockEvents()\n    td.setAnonymousMode()\n  } else if (consented === 'REFUSED') {\n    td.blockEvents()\n  }\n}\n```\n\nThis way, when emerging from Signed or Anonymous mode, you can be sure you'll actually be collecting data in Treasure Data. If the customer has refused all tracking, their events are blocked, and this status will be persisted across page refreshes.\n\n## SameSite cookies\n\n\u003e :warning: **WARNING**: If you see the warnings about `SameSite` cookies in Chrome or Firefox, please upgrade the TreasureData JS SDK to version of at least `2.4.2`\n\nIn recent releases of Chrome and Firefox, they begin enforcing a new secure-by-default cookie classification system, treating cookies that have no declared SameSite value as `SameSite=Lax` cookies. Only cookies set as `SameSite=None; Secure` will be available in third-party contexts, provided they are being accessed from secure connections.\n\nThis affects the **td_client_id** and **td_global_id** cookies in previous versions of TreasureData JS SDK (\u003c 2.4.2) as they are not set as secured cookies.\n\nStarting from version `2.4.2`, TreasureData JS SDK uses `SameSite=None; Secure` cookies as default to adapt the new cookie enforcement.\n\nFor more information:\n\nFirefox:\n\n[Changes to SameSite Cookie Behavior](https://hacks.mozilla.org/2020/08/changes-to-samesite-cookie-behavior/)\n\nChrome:\n\n[SameSite Cookie Changes in February 2020: What You Need to Know](https://blog.chromium.org/2020/02/samesite-cookie-changes-in-february.html)\n\n## API\n\n### Treasure(config)\n\nCreates a new Treasure logger instance.\nIf the database does not exist and you have permissions, it will be created for you.\n\n**Parameters:**\n\n* **config** : Object (required) - instance configuration\n\n**Core parameters:**\n\n* **config.database** : String (required) - database 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.\n* **config.writeKey** : String (required) - write-only key, get it from your [user profile](console.treasuredata.com/users/current)\n* **config.pathname** : String (optional) - path to append after host. Default: `/js/v3/event`\n* **config.host** : String (optional) - host to which events get sent. Default: `in.treasuredata.com`\n* **config.development** : Boolean (optional) - triggers development mode which causes requests to be logged and not get sent. Default: `false`\n* **config.logging** : Boolean (optional) - enable or disable logging. Default: `true`\n* **config.globalIdCookie** : String (optional) - cookie td_globalid name. Default: `_td_global`\n* **config.startInSignedMode** : Boolean (optional) - Tell the SDK to default to Signed Mode if no choice is already made. Default: `false`\n* **config.jsonpTimeout** : Number (optional) - JSONP timeout (in milliseconds) Default: `10000`\n* **config.storeConsentByLocalStorage** : Boolean (optional) - Tell the SDK to use localStorage to store user consent. Default: `false`\n\n**Track/Storage parameters:**\n\n* **config.clientId** : String (optional) - uuid 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\n* **config.storage** : Object | String (optional) - storage configuration object. When `none` it will disable cookie storage\n* **config.storage.name** : String (optional) - cookie name. Default: `_td`\n* **config.storage.expires** : Number (optional) - cookie expiration in seconds. When 0 it will expire with the session. Default: `63072000` (2 years)\n* **config.storage.domain** : String (optional) - cookie domain. Default: result of `document.location.hostname`\n\u003e :warning: NOTE: If **config.storage.domain** would be not set, td-js-sdk may create cookies against multiple domains.\n\u003e For example, suppose you have td-js-sdk located at foo.bar.com.\n\u003e If **config.storage.domain** is not set, td-js-sdk will create two cookies for foo.bar.com and bar.com.\n\u003e In other words, if you don't want cookies created for higher level domains, you need to set domain parameter to the specific domain.\n\n**Server Side Cookie:**\n* **config.useServerSideCookie** : Boolean (optional) - enables/disable using ServerSide Cookie. Default: `false`\n* **config.sscDomain** : String | () =\u003e String (optional) - Domain against which the Server Side Cookie is set. Default: `window.location.hostname`\n* **config.sscServer** : String | (String) =\u003e String (optional) - hostname to request server side cookie from. Default: `ssc.${sscDomain}`\n\n\n**Personalization parameters**\n\n* **config.cdpHost**: String (optional) - The host to use for the Personalization API. Default: 'cdp.in.treasuredata.com'\n\n**Returns:**\n\n* Treasure logger instance object\n\n**Example:**\n\n```javascript\nvar foo = new Treasure({\n  database: 'foo',\n  writeKey: 'your_write_only_key'\n});\n```\n\n### Treasure#addRecord(table, record, success, error)\n\nSends an event to Treasure Data. If the table does not exist it will be created for you.\n\nRecords will have additional properties applied to them if `$global` or table-specific attributes are configured using `Treasure#set`.\n\n:warning: NOTE: 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\nfunction you have to do it manually, as following:\n\n```\ntd.ready(function () {\n   td.set('$global', 'td_ip', 'ip value');\n   td.set('$global', 'td_client_id', td.getTrackValues().td_client_id);\n   td.set('$global', 'td_global_id', 'global id value');\n   \n   td.addRecord(...)\n});\n```\n\n**Parameters:**\n\n* **table** : String (required) - table name, must consist only of lower case letters, numbers, and `_`, must be longer than or equal to 3 chars, the total length of database and table must be shorter than 129 chars.\n* **record** : Object (required) - Object that will be serialized to JSON and sent to the server\n* **success** : Function (optional) - Callback for when sending the event is successful\n* **error** : Function (optional) - Callback for when sending the event is unsuccessful\n\n**Example:**\n\n```javascript\nvar company = new Treasure({...});\n\nvar sale = {\n  itemId: 100,\n  saleId: 10,\n  userId: 1\n};\n\nvar successCallback = function () {\n  // celebrate();\n};\n\nvar errorCallback = function () {\n  // cry();\n}\n\ncompany.addRecord('sales', sale, successCallback, errorCallback);\n```\n\n### Treasure#fetchGlobalID(success, error, forceFetch, options)\n\n**Parameters:**\n\n* **success** : Function (optional) - Callback for when sending the event is successful\n* **error** : Function (optional) - Callback for when sending the event is unsuccessful\n* **forceFetch** : Boolean (optional) - Forces a refetch of global id and ignores cached version (default false)\n* **options** : Object (optional) - Cookie options\n\n**Cookie options:**\n```javascript\n{\n  path: '/',\n  domain: 'abc.com',\n  secure: true|false,\n  maxAge: Number | String | Date,\n  sameSite: 'None | Lax | Strict'\n}\n```\n**Note:**\nIf 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](https://web.dev/samesite-cookies-explained/).\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...})\n\nvar successCallback = function (globalId) {\n  // celebrate();\n};\n\nvar errorCallback = function (error) {\n  // cry();\n}\n\ntd.fetchGlobalID(successCallback, errorCallback)\n\n// with cookie options\ntd.fetchGlobalID(successCallback, errorCallback, false, {\n  path: '/',\n  secure: true,\n  maxAge: 5 * 60 // 5 minutes,\n  sameSite: 'None'\n})\n\n```\n\n### Treasure#fetchUserSegments(options, success, error)\n\n**Parameters:**\n\n* **options** : Object (required) - User Segment object\n  * **options.audienceToken** : String or Array (required) - Audience Token(s) for the userId\n  * **options.keys** : Object (required) - Key Value to be sent for this segment\n* **success** : Function (optional) - Callback for receiving the user key and segments\n* **error** : Function (optional) - Callback for when sending the event is unsuccessful\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...})\n\nvar successCallback = function (values) {\n  /* values format =\u003e [... {\n    key: {\n      [key]:value\n    },\n    values: [\"1234\"],\n    attributes: {\n      age: 30\n    },\n\n  } ... ]*/\n  // celebrate();\n};\n\nvar errorCallback = function (error) {\n  // cry();\n};\n\ntd.fetchUserSegments({\n  audienceToken: ['token1', 'token2'],\n  keys: {\n    someKey: 'someValue',\n    someOtherKey: 'someOtherValue',\n  }\n}, successCallback, errorCallback)\n```\n*N.B.* This feature is not enabled on accounts by default, please contact support for more information.\n\n### Treasure#blockEvents\n\nBlock all events from being sent to Treasure Data.\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...})\ntd.trackEvent('customevent')\ntd.blockEvents()\ntd.trackEvent('willnotbetracked')\n```\n\n### Treasure#unblockEvents\n\nUnblock all events; events will be sent to Treasure Data.\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...})\ntd.blockEvents()\ntd.trackEvent('willnotbetracked')\ntd.unblockEvents()\ntd.trackEvent('willbetracked')\n```\n\n### Treasure#areEventsBlocked\n\nInformational method, expressing whether events are blocked or not.\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...})\ntd.areEventsBlocked() // false, default\ntd.blockEvents()\ntd.areEventsBlocked() // true\n```\n\n### Treasure#setSignedMode\n\nPermit sending of Personally Identifying Information over the wire: td_ip, td_client_id, and td_global_id\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...})\ntd.setSignedMode()\ntd.trackEvent('willbetracked') // will send td_ip and td_client_id; td_global_id will also be sent if set.\n```\n\n### Treasure#setAnonymousMode\n\nProhibit sending of Personally Identifying Information over the wire: td_ip, td_client_id, and td_global_id\n\n**Parameters**:\n* **keepIdentifier**: Boolean (optional) - Keep the cookies\n\nBy 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.\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...})\ntd.setAnonymousMode()\ntd.trackEvent('willbetracked') // will NOT send td_ip and td_client_id; td_global_id will also NOT be sent if set.\n```\n\n### Treasure#inSignedMode\n\nInformational method, indicating whether `trackEvents` method will automatically collect td_ip, td_client_id, and td_global_id if set.\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...})\ntd.inSignedMode() // false, default\ntd.trackEvent('willbetracked') // will NOT send td_ip and td_client_id; td_global_id will also NOT be sent if set.\ntd.setSignedMode()\ntd.inSignedMode() // true\ntd.trackEvent('willbetracked') // will send td_ip and td_client_id; td_global_id will also be sent if set.\n```\n\n### Treasure#fetchServerCookie(success, error, forceFetch)\nThis functionality complies with ITP 1.2 tracking. Contact customer support for enabling this feature.\n\n**Parameters:**\n\n* **success** : Function (optional) - Callback for when sending the event is successful\n* **error** : Function (optional) - Callback for when sending the event is unsuccessful\n* **forceFetch** : Boolean (optional) - Forces a refetch of server side id and ignores cached version (default false)\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...})\n\nvar successCallback = function (serverSideId) {\n  // celebrate();\n};\n\nvar errorCallback = function (error) {\n  // cry();\n}\n\ntd.fetchServerCookie(successCallback, errorCallback)\n```\n\n\n### Treasure#resetUUID\n\n**Parameters:**\n\n* **suggestedStorage** : Object (optional) - Custom storage configuration\n* **suggestedClientId** : String (optional) - Custom client id\n\nReset the client's UUID, set to Treasure Data as `td_client_id`. You can specify custom storage and custom client id.\n\nSee **Track/Storage parameters** section for more information on storage's configuration\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...})\ntd.resetUUID() // set td_client_id as random uuid\n```\n\n```javascript\nvar td = new Treasure({...})\ntd.resetUUID(\n  {\n    name: '_td', // cookie name\n    expires: 63072000,\n    domain: 'domain',\n    customDomain: true/false\n    path: '/'\n  },\n  'xxx-xxx-xxxx' // client id\n)\n```\n\n### Treasure#trackClicks\n\nSetup an event listener to automatically log clicks.\nThe event will be hooked only follows\n- `role=button` or `role=link`\n- `\u003ca\u003e`\n- `\u003cbutton\u003e`\n- `\u003cinput\u003e)`. exclude for `\u003cinput type='password'\u003e`\n\n**Example:**\n```javascript\nvar td = new Treasure({...})\ntd.trackClicks({\n    element         : '...'\n    extendClickData : '...'\n    ignoreAttribute : '...'\n    tableName       : '...'\n    })\n```\n- element: HTMLElement -\u003e 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.\n- extendClickData: Function -\u003e Default is function to set element attributes. You can set function adding special tracking data by extending `function(e: event, elementData: ElementObject)`.\n- ignoreAttribute: string -\u003e Default is `\"td-ignore\"` You can set attribute name to ignore element. (e.g. `\u003cspan role='button' class='button-design' id='button-id' td-ignore /\u003e`)\n- tableName: string -\u003e Default tableName is `\"clicks\"`. Click tracking event will be stored into `tableName` in TreasureData\n\n\n### Treasure#trackPageview(table, success, error)\n\nHelper function that calls trackEvent with an empty record.\n\n**Parameters:**\n\n* **table** : String (required) - table name, must be between 3 and 255 characters and must consist only of lower case letters, numbers, and _\n* **success** : Function (optional) - Callback for when sending the event is successful\n* **error** : Function (optional) - Callback for when sending the event is unsuccessful\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...});\ntd.trackPageview('pageviews');\n```\n\n### Treasure#trackEvent(table, record, success, error)\n\nCreates an empty object, applies all tracked information values, and applies record values. Then it calls `addRecord` with the newly created object.\n\n**Parameters:**\n\n* **table** : String (required) - table name, must be between 3 and 255 characters and must consist only of lower case letters, numbers, and _\n* **record** : Object (optional) - Additional key-value pairs that get sent with the tracked values. These values overwrite default tracking values\n* **success** : Function (optional) - Callback for when sending the event is successful\n* **error** : Function (optional) - Callback for when sending the event is unsuccessful\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...});\n\ntd.trackEvent('events');\n/* Sends:\n{\n  \"td_ip\": \"192.168.0.1\",\n  ...\n}\n*/\n\ntd.trackEvent('events', {td_ip: '0.0.0.0'});\n/* Sends:\n{\n  \"td_ip\": \"0.0.0.0\",\n  ...\n}\n*/\n```\n\n### Treasure#set()\n\nDefault value setter for tables. Set default values for all tables by using `$global` as the setter's table name.\n\n#### Treasure#set(table, key, value)\n\nUseful when you want to set a single value.\n\n**Parameters:**\n\n* **table** : String (required) - table name\n* **key** : String (required) - property name\n* **value** : String | Number | Object (required) - property value\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...})\ntd.set('table', 'foo', 'bar');\ntd.addRecord('table', {baz: 'qux'});\n/* Sends:\n{\n  \"foo\": \"bar\",\n  \"baz\": \"qux\"\n}\n*/\n```\n\n#### Treasure#set(table, properties)\n\nUseful when you want to set multiple values.\n\n**Parameters:**\n\n* **table** : String (required) - table name\n* **properties** : Object (required) - Object with keys and values that you wish applies on the table each time a record is sent\n\n**Example:**\n\n```javascript\nvar td = new Treasure({...})\ntd.set('table', {foo: 'foo', bar: 'bar'});\ntd.addRecord('table', {baz: 'baz'});\n/* Sends:\n{\n  \"foo\": \"foo\",\n  \"bar\": \"bar\",\n  \"baz\": \"baz\"\n}\n*/\n```\n\n\n### Treasure#get(table)\n\nTakes a table name and returns an object with its default values.\n\n**NOTE:** This is only available once the library has loaded. Wrap any getter with a `Treasure#ready` callback to ensure the library is loaded.\n\n**Parameters:**\n\n* **table** : String (required) - table name\n\n**Example:**\n\n```javascript\nvar td = new Treasure({..});\ntd.set('table', 'foo', 'bar');\ntd.get('table');\n// {foo: 'bar'}\n```\n\n\n### Treasure#ready(fn)\n\nTakes a callback which gets called one the library and DOM have both finished loading.\n\n**Parameters:**\n\n* **fn** : Function (required) - callback function\n\n```javascript\n/* javascript snippet here */\nvar td = new Treasure({...})\ntd.set('table', 'foo', 'bar');\n\ntd.ready(function(){\n  td.get('table');\n  // {foo: 'bar'}\n});\n```\n\n## Support\n\nNeed a hand with something? Shoot us an email at [support@treasuredata.com](mailto:support@treasuredata.com)\n\n\n## FAQ\n\n* How does the async script snippet work?\n\nThe async script snippet will create a fake Treasure object on the window and inject the async script tag with the td-js-sdk url. This fake Treasure object includes a fake of all the public methods exposed by the real version. As you call different methods, they will be buffered in memory until the real td-js-sdk has loaded. Upon td-js-sdk loading, it will look for existing clients and process their buffered actions.\n\nThe unminified script loader can be seen in [src/loader.js](src/loader.js). The code to load existing clients and their buffered actions once td-js-sdk has been loaded can be seen in [lib/loadClients.js](lib/loadClients.js).\n\n\n## Other\n\n### Dependency version notes\n\n* `domready` is kept at `0.3.0` for IE6 and above support\n* td-js-sdk doesn't support IE6,7 on version 1.5.2 or later.\n\n## Contributing\n\n### Running the test suite on BrowserStack\n\nFirst you'll need to install `BrowserStackTunnel`. You can download the binary from [the BrowserStack website](https://www.browserstack.com/local-testing). If you're on Mac OS you can install it through homebrew: `brew install caskroom/cask/browserstacklocal`.\n\nNext, you'll need to set the appropriate environment variables:\n - `BROWSER_STACK_BINARY_BASE_PATH`: This should be the directory you put the `BrowserStackTunnel` binary in. If you installed with homebrew you can run `which browserstacklocal` to find the directory.\n - `BROWSER_STACK_USERNAME`: You can find this under the *Automate* section of\nthe [BrowserStack account settings page](https://www.browserstack.com/accounts/settings)\n - `BROWSER_STACK_ACCESS_KEY`: You can find this under the *Automate* section of\nthe [BrowserStack account settings page](https://www.browserstack.com/accounts/settings)\n\nNow, you can run the command `npm run test-full`.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftreasure-data%2Ftd-js-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftreasure-data%2Ftd-js-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftreasure-data%2Ftd-js-sdk/lists"}