From 5cffb5f7483c835e6f30161830798db6a0b45763 Mon Sep 17 00:00:00 2001 From: caseyamp Date: Fri, 11 Mar 2022 09:28:15 -0800 Subject: [PATCH 01/13] First sweep of Javascript SDK and supporting files --- docs/analytics/sdks/android-sdk.md | 29 +- docs/analytics/sdks/javascript-sdk.md | 822 ++++++++++++++++++ .../analytics/sdks/sdk-javascript-overview.md | 639 -------------- includes/group-identify-considerations.md | 6 + includes/logged-out-and-anonymous-users.md | 9 + includes/track-revenue-properties-table.md | 9 + mkdocs.yml | 2 +- vale/styles/Vocab/dev/reject.txt | 1 + 8 files changed, 852 insertions(+), 665 deletions(-) create mode 100644 docs/analytics/sdks/javascript-sdk.md delete mode 100644 docs/analytics/sdks/sdk-javascript-overview.md create mode 100644 includes/group-identify-considerations.md create mode 100644 includes/logged-out-and-anonymous-users.md create mode 100644 includes/track-revenue-properties-table.md create mode 100644 vale/styles/Vocab/dev/reject.txt diff --git a/docs/analytics/sdks/android-sdk.md b/docs/analytics/sdks/android-sdk.md index 13b26b687..2ee45028b 100644 --- a/docs/analytics/sdks/android-sdk.md +++ b/docs/analytics/sdks/android-sdk.md @@ -473,12 +473,7 @@ You can also use `logEventWithGroups` to set event-level groups, meaning the gro --8<-- "includes/editions-growth-enterprise-with-accounts.md" -Use the Group Identify API to set or update properties of particular groups. Keep these considerations in mind: - -- Updates affect only future events, and don't update historical events. -- You can track up to 5 unique group types and 10 total groups. - -The `groupIdentify` method accepts a group type string parameter and group name object parameter, and an Identify object that's applied to the group. +--8<-- "includes/group-identify-considerations.md" === "Java" @@ -513,15 +508,7 @@ Amplitude can track revenue generated by a user. Revenue is tracked through dist Revenue objects support the following special properties, as well as user-defined properties through the `eventProperties` field. -|
Name
| Description | -| --- | --- | -| `productId` | Optional. String. An identifier for the product. Amplitude recommends something like the "Google Play Store product ID". Defaults to `null`. | -| `quantity`| Required. Integer. The quantity of products purchased. Note: revenue = quantity * price. Defaults to 1. | -| `price` | Required. Double. The price of the products purchased, and this can be negative. Note: revenue = quantity * price. Defaults to `null`.| -| `revenueType` | Optional, but required for revenue verification. String. The type of revenue (e.g. tax, refund, income). Defaults to `null`. | -| `receipt` | Optional. String. The type of revenue (e.g. tax, refund, income). Defaults to `null` | -| `receiptSignature` | Optional, but required for revenue verification. The type of revenue (e.g. tax, refund, income). | null | -| `eventProperties`| Optional. JSONObject. An object of event properties to include in the revenue event. Defaults to `null`. | +--8<-- "includes/track-revenue-properties-table.md" !!!note "Notes about tracking revenue" @@ -773,15 +760,7 @@ You can set the log level by calling the following on Android: ## Logged out and anonymous users -Amplitude [merges user data](https://help.amplitude.com/hc/en-us/articles/115003135607#h_c323d7e5-4662-4a36-b0a1-5110a341e80c), so any events associated with a known `userId` or `deviceId` are linked the existing user. - If a user logs out, Amplitude can merge that user's logged-out events to the user's record. You can change this behavior and log those events to an anonymous user instead. - -To log events to an anonymous user: - -1. Set the `userId` to null. -2. Generate a new `deviceId`. - -Events coming from the current user or device appear as a new user in Amplitude. Note: If you do this, you can't see that the two users were using the same device. +--8<-- "includes/logged-out-and-anonymous-users.md" === "Java" @@ -985,7 +964,7 @@ Second, add the following code in your root activity's onCreate life cycle. Android SDK allows users to configure their apps to use [dynamic configuration](https://developers.amplitude.com/docs/dynamic-configuration). This feature finds the best server URL automatically based on app users' location. -- If you have your own proxy server and use `setServerUrl` API, please leave this OFF. +- If you have your own proxy server and use `setServerUrl` API, leave dynamic configuration OFF. - If you have users in China Mainland, we suggest you turn this on. - By default, this feature is OFF. You must explicitly set it to ON to use it. - By default, this feature returns server URL for Amplitude's US servers, if you need to send data to Amplitude's EU servers, please use `setServerZone` to set it to EU zone. diff --git a/docs/analytics/sdks/javascript-sdk.md b/docs/analytics/sdks/javascript-sdk.md new file mode 100644 index 000000000..454b56236 --- /dev/null +++ b/docs/analytics/sdks/javascript-sdk.md @@ -0,0 +1,822 @@ +--- +title: "JavaScript SDK" +icon: material/language-javascript +description: This is the official documentation for the Amplitude JavaScript SDK. +--- + +[![npm version](https://badge.fury.io/js/amplitude-js.svg)](https://badge.fury.io/js/amplitude-js) + +This is the official documentation for the Amplitude JavaScript SDK. + +???info "SDK Resources" + - [JavaScript SDK Reference :material-book:](https://amplitude.github.io/Amplitude-JavaScript/) + - [JavaScript SDK Repository :material-github:](https://github.com/amplitude/Amplitude-JavaScript) + - [JavaScript SDK Releases :material-code-tags-check:](https://github.com/amplitude/Amplitude-Javascript/releases) + +--8<-- "includes/ampli-vs-amplitude.md" + +## SDK Installation + +### Installing Via the Snippet + +You can install the JavaScript SDK using a small snippet of code which you paste on your site to asynchronously load the SDK. + On every page that you want to install Amplitude analytics, paste the code snippet just before the `` tag, replacing API_KEY with the API Key given to you. + You can find your project's API Key in your project's [Settings page](https://help.amplitude.com/hc/en-us/articles/360058073772). + +```js + +``` + +### Installing with npm or yarn + +You can also install the [npm module](https://www.npmjs.com/package/amplitude-js) and embed the SDK directly into your product. + +If you are using npm, use the following command: + +```bash +npm install amplitude-js +``` + +If you are using yarn, use the following command: + +```bash +yarn add amplitude-js +``` + +Now, import amplitude into your project: + +```js +import amplitude from 'amplitude-js'; +``` + +## Usage & Examples + +### Initialization + +Before you can instrument, you must initialize the SDK using the API key for your Amplitude project. + Initialization creates a default instance, but you can create more instances using `getInstance` with a string name. + +```js +var instance1 = amplitude.getInstance().init("API_KEY"); // initializes default instance of Amplitude client +var instance2 = amplitude.getInstance("instance-name").init("API_KEY"); // initializes named instance of Amplitude client +``` + +#### Initialization with Options + +Custom options can be passed into the `init` method. See a [list of options](https://github.com/amplitude/Amplitude-JavaScript/blob/main/src/options.js) on GitHub. + +```js +var options = {}; +var instance = amplitude.getInstance("instance").init("API_KEY", null, options); // initializes with the given options +``` + +### Setting User Id + +Set `userID` when initializing the client, or after initialization with the `setUserId` method. + +=== "Set `userID` on initialization" + + ```js + var userId = "12345"; + amplitude.getInstance().init("API_KEY", userId); // initializes client with the given userId + ``` + +=== "Set `userID` with the `setUserId` method" + + ```js + var userId = "12345"; + amplitude.getInstance().setUserId(userId); + ``` + +### EU Data Residency + +Beginning with version 8.9.0, you can configure the server zone after initializing the client for sending data to Amplitude's EU servers. The SDK sends data based on the server zone if it's set. + The server zone config supports dynamic configuration as well. + +For previous versions, you need to configure the `apiEndpoint` property after initializing the client. + +!!!note + For EU data residency, the project must be set up inside Amplitude EU. You must initialize the SDK with the API key from Amplitude EU. + +```js +// For versions starting from 8.9.0 +// No need to call setServerUrl for sending data to Amplitude's EU servers +amplitude.getInstance().init(euApiKey, null, { + serverZone: 'EU', + serverZoneBasedApi: true, +}); + +// For earlier versions +amplitude.getInstance().init(euApiKey, null, { + apiEndpoint: 'https://api.eu.amplitude.com' +}); +``` + +### Sending Events + +#### Basic Events + +Events represent how users interact with your application. For example, “Button Clicked” may be an action you want to note. + +```js +var event = “Button Clicked”; +amplitude.getInstance().logEvent(event); +``` + +#### Events with Properties + +Events can also contain properties. They provide context about the event taken. For example, “hover time” may be a relevant event property to “Button Clicked”. + +```js +var event = “Button Clicked”; +var eventProperties = { + "hover time": "100ms" +}; +amplitude.getInstance().logEvent(event, eventProperties); +``` + +#### Arrays in Event Properties + +Arrays can be used as event property values. Array event properties can be queried by any subset of the individual properties in the array. + +```js +var event = “Button Clicked”; +var eventProperties1 = { + "selectedColors": ['red', 'blue'] +}; +amplitude.getInstance().logEvent(event, eventProperties1); + +var eventProperties2 = { + "selectedColors": ['red', 'green'] +}; +amplitude.getInstance().logEvent(event, eventProperties2); +``` + +### User Properties + +User properties help you understand your users at the time they performed some action within your app such as their device details, their preferences, or language. + +#### Setting a User Property + +The amplitude Identify object provides controls over setting user properties. + An Identify object must first be instantiated, then Identify methods can be called on it, and finally the client makes a call with the Identify object + +```js +new amplitude.Identify(); // does nothing, must call one of the following methods and pass to client + +var identify = new amplitude.Identify(); +amplitude.getInstance().identify(identify); // makes identify call to amplitude with the properties of the identify object +``` + +#### set + +`set` sets the value of a user property. You can also chain together multiple set calls. + +```js +var identify1 = new amplitude.Identify().set('key1', 'value1'); +var identify2 = new amplitude.Identify().set('key2', 'value2').set('key3', 'value3'); +amplitude.getInstance().identify(identify1); +amplitude.getInstance().identify(identify2); +``` + +#### setOnce + +`setOnce` sets the value of a user property only once. Subsequent calls using `setOnce` will be ignored. + +```js +var identify = new amplitude.Identify().setOnce('key1', 'value1'); +amplitude.getInstance().identify(identify); +``` + +#### add + +`add` increments a user property by some numerical value. If the user property doesn't have a value set yet, it will be initialized to `0` before being incremented. + +```js +var identify = new amplitude.Identify().add('value1', 10); +amplitude.getInstance().identify(identify); + +``` + +#### Setting Multiple User Properties + +You can use `setUserProperties` as a shorthand to set multiple user properties at one time. This method is simply a wrapper around `Identify.set` and `identify`. For example, a user's city can be set with the following code. + +```js +var userProperties = { + city: "San Francisco" +}; +amplitude.getInstance().setUserProperties(userProperties); +``` + +#### Arrays in User Properties + +Arrays can be used as user properties. You can directly set arrays or use `append` to generate an array. + +```js +var values = ['value1', 'value2']; +var identify = new amplitude.Identify().set('key1', values); +amplitude.getInstance().identify(identify); +``` + +#### prepend/append + +- `append` will append a value or values to a user property array. +- `prepend` will prepend a value or values to a user property. + +If the user property doesn't have a value set yet, it will be initialized to an empty list before the new values are added. If the user property has an existing value and it's not a list, it will be converted into a list with the new value added. + +### User Groups + +--8<-- "includes/editions-growth-enterprise-with-accounts.md" + +--8<-- "includes/groups-intro-paragraph.md" + +!!! example + + If Joe is in 'orgId' '10' and '16', then the `groupName` would be '[10, 16]'). Here is what your code might look like: + + ```js + amplitude.getInstance().setGroup('orgId', '[10,16]'); + ``` + +You can also use `logEventWithGroups` to set event-level groups, meaning the group designation only applies for the specific event being logged and doesn't persist on the user unless you explicitly set it with `setGroup`. + +```js +var eventProperties = { + 'key': 'value' +} + +amplitude.getInstance().logEventWithGroups('initialize_game', eventProperties, {'sport': 'soccer'}); +``` + +### Group Identify + +--8<-- "includes/editions-growth-enterprise-with-accounts.md" + +--8<-- "includes/group-identify-considerations.md" + +```js +var groupType = 'plan'; +var groupName = 'enterprise'; +var identify = new amplitude.Identify().set('key1', 'value1'); + +amplitude.getInstance().groupIdentify(groupType, groupName, identify); +``` + +An optional callback function can be supplied as a fourth argument to `groupIdentify`. + +### Track Revenue + +The preferred method of tracking revenue for a user is to use `logRevenueV2()` in conjunction with the provided Revenue interface. Revenue instances will store each revenue transaction and allow you to define several special revenue properties (such as 'revenueType', 'productIdentifier', etc.) that are used in Amplitude's Event Segmentation and Revenue LTV charts. You can also add event properties to revenue events via the eventProperties field. These Revenue instance objects are then passed into `logRevenueV2` to send as revenue events to Amplitude. This allows us to automatically display data relevant to revenue in the platform. You can use this to track both in-app and non-in-app purchases. + +To track revenue from a user, call logRevenueV2() each time a user generates revenue. Here is an example: + +```js +var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3); +amplitude.getInstance().logRevenueV2(revenue); +``` + +Calling `logRevenueV2` will generate a revenue event type: + +- **'[Amplitude] Revenue':** This event is logged for all revenue events, regardless of whether or not verification is turned on. + +You can't change the default names given to these client-side revenue events in the raw data but you do have the option to modify the [display name](https://amplitude.zendesk.com/hc/en-us/articles/235649848#events). To learn more about tracking revenue, see our documentation [here](https://amplitude.zendesk.com/hc/en-us/articles/115003116888). + +!!!note + Amplitude doesn't support currency conversion. All revenue data should be normalized to your currency of choice, before being sent to Amplitude. + +--8<-- "includes/track-revenue-properties-table.md" + +### Opt Out of Tracking + +You can turn off logging for a given user by calling `setOptOut`: + +```js +amplitude.getInstance().setOptOut(true); +``` + +No events are saved or sent to the server while `setOptOut` is enabled. The opt out setting persists across page loads. You can re-enable logging by calling: + +```js +amplitude.getInstance().setOptOut(false); +``` + +### Disable Tracking + +By default, the JavaScript SDK tracks a number of properties automatically. You can override this behavior by passing an object called `trackingOptions` when initializing the SDK, setting the appropriate options to `false`. These options are listed below: + +|
Parameter
| Default Value| +|-------|------------| +|`city` | `true`| +|`country` | `true`| +|`carrier` | `true`| +|`device_manufacturer` | `true`| +|`device_model` | `true`| +|`dma` | `true`| +|`ip_address` | `true`| +|`language` | `true`| +|`os_name` | `true`| +|`os_version` | `true`| +|`platform` | `true`| +|`region` | `true`| +|`version_name` | `true`| + +!!!warning + The *trackingOptions* configurations only prevent default properties from being tracked on new projects, with no existing data. If you have a project with existing data that you would like to stop collecting the default properties for, please contact our Support team at support.amplitude.com. Note that the existing data isn't deleted. + +### Setting Custom User ID + +If your app has its own login system that you want to track users with, you can call `setUserId` at any time: + +```js +amplitude.getInstance().setUserId('USER_ID'); +``` + +You can also add the User ID as an argument to the init call. + +```js +[[Amplitude] instance] initializeApiKey:@"API_KEY" userId:@"USER_ID"]; +``` + +Don't assign users a user ID that could change as each unique user ID is interpreted as a unique user in Amplitude. For more information see [Track unique users in Amplitude](https://help.amplitude.com/hc/en-us/articles/115003135607-Track-unique-users-in-Amplitude) in the Help Center. + +### Log Out and Anonymous Users + +--8<-- "includes/logged-out-and-anonymous-users.md" + +```js +amplitude.getInstance().setUserId(null); // not string 'null' +amplitude.getInstance().regenerateDeviceId(); +``` + +### Session Tracking + +Events triggered within 30 minutes of each other are counted towards the current session. The time of the first event marks the start time of a session and the last event triggered marks the end time of a session. You can change the session timeout window via the SDK configuration option field sessionTimeout. + +#### Getting the Session ID + +In the JavaScript SDK, you can use the helper method _sessionId to get the value of the current sessionId: + +```js +var sessionId = amplitude.getInstance()._sessionId; +``` + +### Configuring HTTP Headers + +HTTP request headers that are attached to sent events can be set using the `options.headers` configuration when initializing. This should only be relevant if a [domain proxy](https://developers.amplitude.com/docs/domain-proxies) is used that requires custom header options. + +```js +amplitude.getInstance().init(APIKEY, null, { + headers: { + 'x-session-id': appToken, + 'Content-Type': 'application/json;charset=utf-8' + } +}); +``` + +### Logging Events to Multiple Projects + +If you want to log events to multiple Amplitude projects, then must have separate instances for each Amplitude project. As mentioned earlier, each instance allows for independent `apiKeys`, `userIds`, `deviceIds`, and settings. + +You must assign a name to each Amplitude project and instance and use that name consistently when fetching that instance to call functions. + +!!!important + After you have chosen a name for that instance you can't change it. + Choose your instance names wisely. Every instance's data and settings are tied to its name, and you must continue using that instance name for all future versions of your project to maintain data continuity. + Instance names don't need be the names of your projects in the Amplitude platform, but they need to remain consistent throughout your code. You also need to be sure that each instance is initialized with the correct `apiKey`. + +Instance names must be non-null and non-empty strings. Names are case insensitive, and you can fetch each instance name by calling. + +Each new instance has its own `apiKey`, `userId`, `deviceId`, and settings. + +The following is an example of how to set up and log events to two separate projects: + +```js +// existing project, existing settings, and existing API key +amplitude.getInstance().init('12345', null, {batchEvents: true}); +// new project, new API key +amplitude.getInstance('new_project').init('67890', null, {includeReferrer: true}); + +// need to reconfigure new project +amplitude.getInstance('new_project').setUserId('joe@gmail.com'); +amplitude.getInstance('new_project').setUserProperties({'gender':'male'}); +amplitude.getInstance('new_project').logEvent('Clicked'); + +var identify = new amplitude.Identify().add('karma', 1); +amplitude.getInstance().identify(identify); +amplitude.getInstance().logEvent('Viewed Home Page'); +``` + +### Web Attribution + +While Amplitude’s Javascript SDK doesn't collect web attribution data by default, setting it up is simple. The SDK can automatically collect this information if certain attribution configuration options are enabled. + +Amplitude supports automatically tracking the following through the SDK configuration options: + +- The 5 standard UTM parameters from the user's browser cookie or URL parameters by using `includeUtm`. +- The referring URL and domain from includeReferrer. +- Google Click Identifier from URL parameters through `includeGclid`. +- Facebook Click Identifier from URL parameters through `includeFbclid`. + +#### Track UTM Parameters + +UTM parameters stand for Urchin Traffic Monitor parameters and are useful for analyzing the effectiveness of different ad campaigns and referring sites. + UTM parameters are case sensitive so they're considered different values if the capitalization varies. + +There are five different standard UTM parameters: + +- `utm_source`: This identifies which website sent the traffic (e.g. Google, Facebook). +- `utm_medium`: This identifies what type of link was used (e.g. banner, button, email). +- `utm_campaign`: This identifies a specific campaign used (e.g. summer_sale). +- `utm_term`: This identifies paid search terms used (e.g. product+analytics). +- `utm_content`: This identifies what brought the user to the site and is commonly used for A/B testing (e.g. bannerlink, textlink). + +Here is an example URL: + +`https://www.amplitude.com/?utm_source=newsletter&utm_campaign=product_analytics_playbook&utm_medium=email&utm_term=product%20analytics&utm_content=bannerlink` + +#### Enabling via SDK + +In Amplitude, after you set the `includeUtm` option to true, the JavaScript SDK automatically pulls UTM parameters from the referring URL and include them as user properties on all relevant events: + +- **includeGclid:** Gclid (Google Click Identifier) is a globally unique tracking parameter used by Google. If utilized, Google will append a unique parameter (e.g. "?gclid=734fsdf3") to URLs at runtime. By setting this to true, the SDK captures `initial_glid` and `gclid` as user properties. +- **includeFbclid:** Fbclid (Facebook Click Identifier) is a globally unique tracking parameter used by Facebook. If utilized, Facebook will append a unique parameter (e.g. "?fbclid=392foih3") to URLs at runtime. By setting this to true, the SDK captures `initial_fblid` and `fbclid` as user properties. +- **includeUtm:** If true, finds the standard UTM parameters from either the URL or the browser cookie and sets them as user properties. This sets `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, and `utm_content` as well as `initial_utm_source`, `initial_utm_medium`, `initial_utm_campaign`, `initial_utm_term`, and `initial_utm_content` as user properties for the user. +UTM parameters are captured once per session by default and occurs when the user loads your site and the Amplitude SDK for the first time. You can disable the once per session restriction through the saveParamsReferrerOncePerSession configuration option. When the SDK detects that it should start a new session, it pulls the UTM parameters that are available at the time. Those UTM parameters will be set as user properties which persists for all of the user's events going forward. However, initial UTM parameters are captured only once for each user via a setOnce operation. + +#### Track Referrers + +If you want to track how users are getting to your website, then all you need to do is track the referrer (the referring site). + +Here are the fields Amplitude supports tracking automatically: + +- `referrer`: The last page the user was on (e.g. ). +- `referring_domain`: The domain that the user was last on (e.g. amplitude.com). + +#### Enabling via SDK + +Once you set the `includeReferrer` option to `true`, Amplitude captures the `referrer` and `referring_domain` for each session and set them as user properties on relevant events: + +- `includeReferrer`: When `true`, captures the `referrer` and `referring_domain` for each session as user properties as well as the `initial_referrer` and `initial_referring_domain` user properties once for each user. + The referrer is the entire URL while the referring_domain is only the domain name from where the user came from. + +Initial referring information is captured only once for each user via a `setOnce` operation. + +#### First-Touch Attribution + +Amplitude can capture the initial UTM parameters and referrer information for each user. The first-touch attribution values are set when a user's non-null UTM parameters are seen for the first time. The following user properties are set once: + +- `initial_utm_source` +- `initial_utm_medium` +- `initial_utm_campaign` +- `initial_utm_term` +- `initial_utm_content` +- `initial_referrer` +- `initial_referring_domain` +- `initial_gclid` +- `initial_fbclid` + +This is done by setting the JavaScript SDK configuration options `includeReferrer`, `includeUtm`, and `includeGclid` to `true`. + +!!!note + Initial attribution information for users can change if they are merged with another user. + +#### Last-Touch Attribution + +In addition to first-touch attribution, Amplitude will capture where a user came from for each of their sessions. This is accomplished by setting the following user properties: + +- `utm_source` +- `utm_medium` +- `utm_campaign` +- `utm_term` +- `utm_content` +- `referrer` +- `referring_domain` +- `gclid` +- `fbclid` + +This is done by setting the JavaScript SDK configuration options `includeReferrer`, `includeUtm`, and `includeGclid` to `true`. By default, the SDK will only save values at the start of the session so if a user triggers some flow that causes them to land on the site again with a different set of UTM parameters within the same session, that second set will not be saved. + +#### Multi-Touch Attribution + +If you set `saveParamsReferrerOncePerSession` to `false` in your JavaScript SDK configuration, the SDK will always capture any new values from the user. This updates these user properties throughout a session if they change: + +- `utm_source` +- `utm_medium` +- `utm_campaign` +- `utm_term` +- `utm_content` +- `referrer` +- `referring_domain` +- `gclid` +- `fbclid` + +Some customers also instrument these user properties as arrays to keep track of all the attribution parameters seen within the same session for a single user. + +#### Logging Captured Attribution Values via Amplitude (Advanced Use Case) + +!!!important + + These events count towards your event quota. + +If you set `logAttributionCapturedEvent` to `true` in your JavaScript SDK configuration, the SDK logs an Amplitude event anytime new attribution values are captured from the user. + +**Event Name:** [Amplitude] Attribution Captured + +**Event Properties:** + +- `utm_source` +- `utm_medium` +- `utm_campaign` +- `utm_term` +- `utm_content` +- `referrer` +- `referring_domain` +- `gclid` +- `fbclid` + +### Google Tag Manager + +Amplitude's JavaScript SDK supports integration with Google Tag Manager. Take a look at our demo application for instructions on how to set it up. + +### Dynamic Configuration + +Beginning with version 8.9.0, the JavaScript SDK allows users to configure their apps to use [dynamic configuration](https://developers.amplitude.com/docs/dynamic-configuration). This feature finds the best server URL automatically based on app users' location. + +- If you have your own proxy server and use `apiEndPoint` API, leave dynamic configuration OFF. +- If you have users in China Mainland, we suggest you turn this on. +- By default, this feature is OFF. You must explicitly set it to ON to use it. +- By default, this feature returns server URL of Amplitude's US servers, if you need to send data to Amplitude's EU servers, please use `setServerZone` to set it to EU zone. + +```js +amplitude.getInstance().init(euApiKey, null, { + useDynamicConfig: true, +}); +``` + +## Advanced topics + +### Getting the Device ID + +You can get a user's current Device ID with the following code: + +```js +var deviceId = amplitude.getInstance().options.deviceId; // existing device id +``` + +### Setting Configuration Options + +You can configure Amplitude by passing an object as the third argument to the init: + +```js +amplitude.getInstance().init("API_KEY", null, { + // optional configuration options + saveEvents: true, + includeUtm: true, + includeReferrer: true +}) +``` + +### Cookie Management + +#### Cookies Created by the SDK + +On initialization, the SDK will create a cookie that begins with the prefix `amp_` and ends with this first six digits of your API key. For example `amplitude.getInstance().init("a2dbce0e18dfe5f8e74493843ff5c053")` would create a cookie with the key `amp_a2dbce`. + +The cookie is used to keep track of a few bits of metadata for the SDK: + +- A randomly generated device id +- The current session id +- The current user id if a user id is set +- The last event time +- A few sequence ids in order to sequence events and identifies correctly + +#### Disabling Cookies + +Amplitude cookies can be disabled altogether using the `disableCookies` option. When you disable cookies, the JavaScript SDK will fallback to using `localStorage` to store its data. LocalStorage is a great alternative, but there is one small potential downside. If you track anonymous users across subdomains of your product (eg: `www.amplitude.com` vs `analytics.amplitude.com`), this doesn't work. Access to localStorage is restricted by subdomain. + +#### SameSite + +The JavaScript SDK defaults to setting the SameSite option on its cookies to `None`. This can be overridden with the `sameSiteCookie` option. We set the option to `Lax` option on our own sites at amplitude. Lax is recommended unless there are instances where you have third party sites that `POST` forms to your site. The default may change to `Lax` in the future. + +#### HttpOnly Cookies + +An HttpOnly option isn't technologically possible for Amplitude's SDK cookies. The cookie is set on the client side and is used as a client-side data store. An SDK cookie can't set the HttpOnly flag. + +#### Upgrading Legacy Cookies + +Historically, Amplitude's cookies have been on the large side. Newly created cookies tend to be significantly smaller. For users that already have older cookies saved, the SDK will only remove old cookies and start using the newer more compact cookie format if the `cookieForceUpgrade` option is set to `true`. Note that if you use the SDK in multiple products, and track anonymous users across those products, you will want to be sure to set this option on all of those products. We would only recommend doing this if you are running into problems with over sized cookies. + +### RequireJS + +If you are using RequireJS to load your JavaScript files, then you can also use it to load the Amplitude JavaScript SDK script directly instead of using our loading snippet. If you take this approach you will lose one of the key advantages of the snippet that allows your app to start and use the Amplitude SDK without having to wait for Amplitude to fully download. + +```js + + +``` + +You can also define the path in your RequireJS configuration like this: + +```js + + + +``` + +### Cross Domain Tracking (JavaScript) + +You can track anonymous behavior across two different domains. Anonymous users are identified by their Device IDs which will need to be passed between the domains. For example: + +- Site 1: `www.example.com` +- Site 2: `www.example.org` + +Users who start on Site 1 and then navigate to Site 2 will need to have the Device ID generated from Site 1 passed as a parameter to Site 2. Site 2 then needs to initialize the SDK with that Device ID. The SDK can parse the URL parameter automatically if `deviceIdFromUrlParam` is enabled. + +- From Site 1, grab the Device ID from `amplitude.getInstance().options.deviceId`. +- Pass the Device ID to Site 2 via a URL parameter when the user navigates. (e.g. `www.example.com?amp_device_id=device_id_from_site_1`) +- Initialize the Amplitude SDK on Site 2 with `amplitude.init('API_KEY', null, {deviceIdFromUrlParam: true})`. + +### Tracking UTM Parameters, Referrer, and gclid (JavaScript) + +Amplitude supports automatically tracking: + +- Standard UTM parameters from the user's cookie or URL parameters when the configuration option includeUtm is set to true during initialization. +- The referring URL when the configuration option includeReferrer is set to true during initialization. +- gclid (Google Click ID) from URL parameters when the configuration option includeGclid is set to true during initialization. + +If tracking is enabled, then the SDK will set the values as user properties (e.g. referrer or utm_source) once per session (this is last touch attribution). The SDK will also save the initial values using a setOnce operation (e.g. initial_referrer or initial_utm_source), and once set that value will never change (this is first touch attribution). + +*Note: By default, the SDK will only save the values at the start of the session.* For example, if a user lands on your site with an initial set of UTM parameters and triggers some flow that causes them to land on your site again with a different set of UTM parameters within the same Amplitude session, then that second set isn't saved. You can set the configuration option saveParamsReferrerOncePerSession to false to remove that restriction so that the SDK will always capture any new values from the user. + +*Note: By default, the SDK will carry over existing UTM Parameters and Referrer values at the start of a new session.* For example, if a users session expires, the SDK will map the user's Referrer and UTM Parameters to existing values. *To reset those values to null upon instantiating a new session, set unsetParamsReferrerOnNewSession to true.* + +### Callbacks for logEvent, Identify, and Redirect + +You can pass a callback function to logEvent and identify, which will get called after receiving a response from the server. This is useful if timing may cause an event to not be captured before the browser navigates away from a webpage. Putting the navigation in a callback to the logEvent method will guarantee the event is captured before the navigation occurs. Here is a logEvent example: + +```js +amplitude.getInstance().logEvent("EVENT_TYPE", null, callback_function); +``` + +Here is an identify example: + +```js +var identify = new amplitude.Identify().set('key', 'value'); +amplitude.getInstance().identify(identify, callback_function); +``` + +The status and response body from the server are passed to the callback function, which you might find useful. Here is an example of a callback function which redirects the browser to another site after a response: + +```js +var callback_function = function(status, response) { + if (status === 200 && response === 'success') { + // do something here + } + window.location.replace('URL_OF_OTHER_SITE'); +}; +``` + +You can also use this to track outbound links to your website. For example, you would have a link like this: + +```js +Link A +``` + +Then, you would define a function that'scalled when the link is clicked like this: + +```js +var trackClickLinkA = function() { + amplitude.getInstance().logEvent('Clicked Link A', null, function() { + window.location='LINK_A_URL'; + }); +}; +``` + +In the case that optOut is true, then no event is logged but the callback will be called. In the case that batchEvents is true, if the batch requirements eventUploadThreshold and eventUploadPeriodMillis aren't met when logEvent is called, then no request is sent but the callback is still called. In these cases, the callback will be called with an input status of 0 and a response of 'No request sent'. + +### Error Callbacks + +You can pass a second callback to `logEvent` and identify that will be called if the network request for the event fails. This is useful to detect if a user is using an ad blocker, or if there's an error from the Amplitude server due to an issue with the event format. You can use the error callback together with the success callback like this: + +```js +var successCallback = function() { + console.log('the event was logged successfully'); +} + +var errorCallback = function() { + console.log('there was an error logging the event') +}; + +amplitude.getInstance().logEvent('event', null, successCallback, errorCallback); +``` + +### init Callbacks + +You can also pass a callback function to init, which will get called after the SDK finishes its asynchronous loading. Note: The instance is passed as an argument to the callback: + +```js +amplitude.getInstance().init('API_KEY', 'USER_ID', null, function(instance) { + console.log(instance.options.deviceId); // access Amplitude's deviceId after initialization +}); +``` + +### Using sendBeacon + +In SDK version 8.5.0 and above, the SDK can send events using the browser's built-in navigator.sendBeacon API. Unlike standard network requests, events sent by sendBeacon are sent in the background, and will be completed even if the user quickly closes the browser or leaves the page. However, because these events are sent in the background, it's not known if the event successfully uploads to the Amplitude server, and can't be saved for a later retry. + +To send an event using sendBeacon, set the transport SDK option to 'beacon' in one of two ways + +```js +// set transport to 'beacon' when initializing an event +amplitude.getInstance().init('API_KEY', 'USER_ID', {transport: 'beacon'}); + +// set transport to 'beacon' after initialization +amplitude.getInstance().setTransport('beacon'); + +// this event will be sent using navigator.sendBeacon +amplitude.getInstance().logEvent('send event with beacon'); + +// set transport back to the default 'http' value +amplitude.getInstance().setTransport('http'); + +// this event will be sent using the standard xhr mechanism +amplitude.getInstance().logEvent('send event with http'); + +``` + +#### Using sendBeacon only when exiting page + +Configuring sendBeacon to send data only when the user exits a page can be complicated, so the JavaScript SDK provides a convenient callback function that's called only when the user exits the page, and automatically switches the transport to 'beacon' for any logs sent in the callback. This callback is called 'onExitPage' and is passed into the SDK on initialization, like so: + +```js +var exitCallback = function { + amplitude.getInstance().logEvent('Logging a final event as user exits via sendBeacon'); +}; + +amplitude.getInstance().init('API_KEY', 'USER_ID', { onExitPage: exitCallback }); +``` + +### Custom Device IDs + +By default, device IDs are randomly generated UUIDs, although you can define a custom device ID by setting it as a configuration option or by calling: + +```js +amplitude.getInstance().setDeviceId('DEVICE_ID'); +``` + +You can retrieve the Device ID that Amplitude uses with `Amplitude.getInstance().getDeviceId().` This method can return `null` if a `deviceId` hasn't been generated yet. + +!!!note + This isn't recommended unless you have your own system for tracking user devices. Make sure the `deviceId` you set is unique to prevent conflicts with other devices in your Amplitude data. We recommend something like a UUID. + +See [here](https://github.com/amplitude/Amplitude-Javascript/blob/master/src/uuid.js) for an example of how to generate on JavaScript. diff --git a/docs/analytics/sdks/sdk-javascript-overview.md b/docs/analytics/sdks/sdk-javascript-overview.md deleted file mode 100644 index 6598904c7..000000000 --- a/docs/analytics/sdks/sdk-javascript-overview.md +++ /dev/null @@ -1,639 +0,0 @@ ---- -title: "JavaScript SDK" -tags: - - javascript - - sdk -icon: material/language-javascript -hide: - - tags ---- -# JavaScript SDK - -[![npm version](https://badge.fury.io/js/amplitude-js.svg)](https://badge.fury.io/js/amplitude-js) - -???info "SDK Resources" - - [JavaScript SDK Reference :material-book:](https://amplitude.github.io/Amplitude-JavaScript/) - - [JavaScript SDK Repo :material-github:](https://github.com/amplitude/Amplitude-JavaScript) - - [JavaScript SDK Releases :material-code-tags-check:](https://github.com/amplitude/Amplitude-Javascript/releases) - - -## SDK Installation - -### Installing Via the Snippet - -You can install the JavaScript SDK using a small snippet of code which you paste on your site to asynchronously load the SDK. On every page that you want to install Amplitude analytics, paste the code snippet just before the `` tag, replacing API_KEY with the API Key given to you. You can find your project's API Key in your project's [Settings page](https://help.amplitude.com/hc/en-us/articles/360058073772). - -```javascript - -``` - -### Installing with npm or yarn - - Alternatively, you can install the [npm module](https://www.npmjs.com/package/amplitude-js) and embed the SDK directly into your product. -If you are using npm, use the following command: - -```javascript -npm install amplitude-js -``` - -If you are using yarn, use the following command: - -```javascript -yarn add amplitude-js -``` - -You will now be able to import amplitude in your project: - -```javascript -import amplitude from 'amplitude-js'; -``` - -## Usage & Examples - -### Initialization - -Initialization is necessary before any instrumentation is done. The API key for your Amplitude project is required. The default instance will be created by default, but several instances can be maintained if created through `getInstance` with a string name. - -```javascript -var instance1 = amplitude.getInstance().init("API_KEY"); // initializes default instance of Amplitude client -var instance2 = amplitude.getInstance("instance").init("API_KEY"); // initializes named instance of Amplitude client -``` - -#### Initialization with Options - -Custom options can be passed into the init method. A list of all possible options for the client can be found [here](https://github.com/amplitude/Amplitude-JavaScript/blob/main/src/options.js). - -```javascript -var options = {}; -var instance = amplitude.getInstance("instance").init("API_KEY", null, options); // initializes with the given options -``` - -### Setting User Id - -The User ID can be set either upon initializing the client, or after initialization with the `setUserId` method. - -```javascript -var userId = "12345"; -amplitude.getInstance().init("API_KEY", userId); // initializes client with the given userId -``` - -```javascript -var userId = "12345"; -amplitude.getInstance().setUserId(userId); -``` - -### EU Data Residency - -Starting from version 8.9.0, you can configure the server zone when initializing the client for sending data to Amplitude's EU servers. SDK will switch and send data based on the server zone if it is set. The server zone config supports dynamic configuration as well. - -For previous versions, you need to configure the apiEndpoint property when initializing the client. - -Warning: For EU data residency, project need to be set up inside Amplitude EU and SDK initialized with api key from Amplitude EU first. This method won't work without proper set up first. -[block:code] -{ - "codes": [ - { - "code": "// For versions starting from 8.9.0\n// No need to call setServerUrl for sending data to Amplitude's EU servers\namplitude.getInstance().init(euApiKey, null, {\n serverZone: 'EU',\n serverZoneBasedApi: true,\n});\n\n// For earlier versions\namplitude.getInstance().init(euApiKey, null, {\n apiEndpoint: 'https://api.eu.amplitude.com'\n});", - "language": "javascript" - } - ] -} -[/block] - -### Sending Events - -#### Basic Events - -Events represent how users interact with your application. For example, “Button Clicked” may be an action you want to note. - -```javascript -var event = “Button Clicked”; -amplitude.getInstance().logEvent(event); -``` - -#### Events with Properties - -Events can also contain properties. They provide context about the event taken. For example, “hover time” may be a relevant event property to “Button Clicked”. - -```javascript -var event = “Button Clicked”; -var eventProperties = { - "hover time": "100ms" -}; -amplitude.getInstance().logEvent(event, eventProperties); -``` - -#### Arrays in Event Properties - -Arrays can be used as event property values. Array event properties can be queried by any subset of the individual properties in the array. - -```javascript -var event = “Button Clicked”; -var eventProperties1 = { - "selectedColors": ['red', 'blue'] -}; -amplitude.getInstance().logEvent(event, eventProperties1); - -var eventProperties2 = { - "selectedColors": ['red', 'green'] -}; -amplitude.getInstance().logEvent(event, eventProperties2); -``` - -### User Properties - -User properties help you understand your users at the time they performed some action within your app such as their device details, their preferences, or language. - -#### Setting a User Property - -The amplitude Identify object provides controls over setting user properties. An Identify object must first be instantiated, then Identify methods can be called on it, and finally the client will make a call with the Identify object - -```javascript -new amplitude.Identify(); // does nothing, must call one of the following methods and pass to client - -var identify = new amplitude.Identify(); -amplitude.getInstance().identify(identify); // makes identify call to amplitude with the properties of the identify object -``` - -#### set - -`set` sets the value of a user property. You can also chain together multiple set calls. - -```javascript -var identify1 = new amplitude.Identify().set('key1', 'value1'); -var identify2 = new amplitude.Identify().set('key2', 'value2').set('key3', 'value3'); -amplitude.getInstance().identify(identify1); -amplitude.getInstance().identify(identify2); -``` - -#### setOnce - -`setOnce` sets the value of a user property only once. Subsequent calls using `setOnce` will be ignored. - -```javascript -var identify = new amplitude.Identify().setOnce('key1', 'value1'); -amplitude.getInstance().identify(identify); -``` - -#### add - -`add` increments a user property by some numerical value. If the user property does not have a value set yet, it will be initialized to `0` before being incremented. - -```javascript -var identify = new amplitude.Identify().add('value1', 10); -amplitude.getInstance().identify(identify); - -``` - -#### Setting Multiple User Properties - -You can use `setUserProperties` as a shorthand to set multiple user properties at once. This method is simply a wrapper around `Identify.set` and `identify`. For example, a user's city can be set with the following code. - -```javascript -var userProperties = { - city: "San Francisco" -}; -amplitude.getInstance().setUserProperties(userProperties); -``` - -#### Arrays in User Properties - -Arrays can be used as user properties. You can directly set arrays or use `append` to generate an array. - -```javascript -var values = ['value1', 'value2']; -var identify = new amplitude.Identify().set('key1', values); -amplitude.getInstance().identify(identify); -``` - -#### prepend/append - -- `append` will append a value or values to a user property array. -- `prepend` will prepend a value or values to a user property. - -If the user property does not have a value set yet, it will be initialized to an empty list before the new values are added. If the user property has an existing value and it is not a list, it will be converted into a list with the new value added. - -### User Groups - -[block:callout] -{ - "type": "info", - "body": "Note: This feature is only available for Growth customers who have purchased the [Accounts add-on](https://amplitude.zendesk.com/hc/en-us/articles/115001765532)." -} -[/block] - -Amplitude supports assigning users to groups and performing queries such as Count by Distinct on those groups. An example would be if you want to group your users based on what organization they are in by using an 'orgId'. You can designate Joe to be in 'orgId' '10' while Sue is in 'orgId' '15'. When performing a query in our Event Segmentation chart, you can then select "..performed by" 'orgId' to query the number of different organizations that have performed a specific event. As long as at least one member of that group has performed the specific event, that group will be included in the count. - -When setting groups, you will need to define a groupType and groupName(s). In the above example, 'orgId' is the groupType and the values '10' and '15' are groupName(s). Another example of a groupType could be 'sport' with groupName(s) like 'tennis' and 'baseball'. You can use setGroup(groupType, groupName) to designate which groups a user belongs to. Note: This will also set the 'groupType:groupName' as a user property. This will overwrite any existing groupName value set for that user's groupType, as well as the corresponding user property value. groupType is a string and groupName can be either a string or an array of strings to indicate a user being in multiple groups (for example, if Joe is in 'orgId' '10' and '16', then the groupName would be '[10, 16]'). Here is what your code might look like. -[block:code] -{ - "codes": [ - { - "code": "amplitude.getInstance().setGroup('orgId', '15');\namplitude.getInstance().setGroup('sport', ['soccer', 'tennis']);", - "language": "javascript" - } - ] -} -[/block] -You can also use logEventWithGroups to set event-level groups, meaning the group designation only applies for the specific event being logged and does not persist on the user unless you explicitly set it with setGroup. -[block:code] -{ - "codes": [ - { - "code": "var eventProperties = {\n 'key': 'value'\n}\n\namplitude.getInstance().logEventWithGroups('initialize_game', eventProperties, {'sport': 'soccer'});", - "language": "javascript" - } - ] -} -[/block] - -### Group Identify - -!!!note - (Enterprise only) This feature is only available to Growth and Enterprise customers who have purchased the [Accounts add-on](https://amplitude.zendesk.com/hc/en-us/articles/115001765532). - -Use the Group Identify API to set or update properties of particular groups. However, these updates will only affect events going forward. - -The `groupIdentify` method accepts a group type and group name string parameter, as well as an Identify object that will be applied to the group. - -```javascript -var groupType = 'plan'; -var groupName = 'enterprise'; -var identify = new amplitude.Identify().set('key1', 'value1'); - -amplitude.getInstance().groupIdentify(groupType, groupName, identify); -``` - -An optional callback function can be supplied as a fourth argument to `groupIdentify`. - -### Track Revenue - -The preferred method of tracking revenue for a user is to use `logRevenueV2()` in conjunction with the provided Revenue interface. Revenue instances will store each revenue transaction and allow you to define several special revenue properties (such as 'revenueType', 'productIdentifier', etc.) that are used in Amplitude's Event Segmentation and Revenue LTV charts. You can also add event properties to revenue events via the eventProperties field. These Revenue instance objects are then passed into `logRevenueV2` to send as revenue events to Amplitude. This allows us to automatically display data relevant to revenue in the platform. You can use this to track both in-app and non-in-app purchases. - -To track revenue from a user, call logRevenueV2() each time a user generates revenue. Here is an example: -[block:code] -{ - "codes": [ - { - "code": "var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3);\namplitude.getInstance().logRevenueV2(revenue);", - "language": "javascript" - } - ] -} -[/block] -Calling logRevenueV2 will generate a revenue event type: - -- **'[Amplitude] Revenue':** This event is logged for all revenue events, regardless of whether or not verification is turned on. - -You cannot change the default names given to these client-side revenue events in the raw data but you do have the option to modify the [display name](https://amplitude.zendesk.com/hc/en-us/articles/235649848#events). To learn more about tracking revenue, see our documentation [here](https://amplitude.zendesk.com/hc/en-us/articles/115003116888). - -**IMPORTANT NOTE: Amplitude currently does not support currency conversion. All revenue data should be normalized to your currency of choice, before being sent to Amplitude.** - -Name | Type | Description | Default ------|-------|--------------|-------- -productId (optional) | string | An identifier for the product. We recommend something like the Google Play Store product ID. | null -quantity (required) | integer | The quantity of products purchased. Note: revenue = quantity * price | 1 -price (required) | double | The price of the products purchased, and this can be negative. Note: revenue = quantity * price | null -revenueType (optional) | string | The type of revenue (e.g. tax, refund, income). | null -eventProperties (optional) | object | An object of event properties to include in the revenue event. | null - -### Opt Out of Tracking - -You can turn off logging for a given user by calling setOptOut: -[block:code] -{ - "codes": [ - { - "code": "amplitude.getInstance().setOptOut(true);", - "language": "javascript" - } - ] -} -[/block] -No events will be saved or sent to the server while this is enabled. The opt out setting will persist across page loads. You can reenable logging by calling: -[block:code] -{ - "codes": [ - { - "code": "amplitude.getInstance().setOptOut(false);", - "language": "text" - } - ] -} -[/block] - -### Disable Tracking - -By default, the JS SDK will track a number of properties automatically. You can override this behavior by passing an object called `trackingOptions` when initializing the SDK, setting the appropriate options to `false`. These options are listed below: - -Parameter | Default Value --------|------------ -city | true -country | true -carrier | true -device_manufacturer | true -device_model | true -dma | true -ip_address | true -language | true -os_name | true -os_version | true -platform | true -region | true -version_name | true -[block:callout] -{ - "type": "warning", - "body": "The *trackingOptions* configurations will only prevent default properties from being tracked on **newly created** projects, where data has not yet been sent. If you have a project with existing data that you would like to stop collecting the default properties for, please contact our Support team at support.amplitude.com. Note that the existing data will not be deleted.", - "title": "Important Note" -} -[/block] - -### Setting Custom User ID - -If your app has its own login system that you want to track users with, you can call setUserId at any time: -[block:code] -{ - "codes": [ - { - "code": "amplitude.getInstance().setUserId('USER_ID');", - "language": "javascript" - } - ] -} -[/block] -You can also add the User ID as an **argument** to the init call。 -[block:code] -{ - "codes": [ - { - "code": "[[Amplitude] instance] initializeApiKey:@\"API_KEY\" userId:@\"USER_ID\"];", - "language": "javascript" - } - ] -} -[/block] -You should not assign users a User ID that could change as each unique User ID is interpreted as a unique user in Amplitude. Please see our article on how we identify and count unique users for further information. - -### Log Out and Anonymous Users - -A user's data will be [merged](https://help.amplitude.com/hc/en-us/articles/115003135607) on the backend so that any events up to that point from the same browser will be tracked under the same user. If a user logs out or you want to log the events under an anonymous user, you will need to: - -1. Set the userId to null. -2. Regenerate a new deviceId. - -After doing that, events coming from the current user/device will appear as a brand new user in Amplitude. Note: If you choose to do this, you will not be able to see that the two users were using the same device. -[block:code] -{ - "codes": [ - { - "code": "amplitude.getInstance().setUserId(null); // not string 'null'\namplitude.getInstance().regenerateDeviceId();", - "language": "javascript" - } - ] -} -[/block] - -### Session Tracking - -Events triggered within 30 minutes of each other are counted towards the current session. The time of the first event marks the start time of a session and the last event triggered marks the end time of a session. You can change the session timeout window via the SDK configuration option field sessionTimeout. - -#### Getting the Session ID - -In the JavaScript SDK, you can use the helper method _sessionId to get the value of the current sessionId: -[block:code] -{ - "codes": [ - { - "code": "var sessionId = amplitude.getInstance()._sessionId;", - "language": "javascript" - } - ] -} -[/block] - -### Configuring HTTP Headers - -HTTP request headers that are attached to sent events can be set using the `options.headers` configuration when initializing. This should only be relevant if a [domain proxy](https://developers.amplitude.com/docs/domain-proxies) is used that requires custom header options. - -[block:code] -{ - "codes": [ - { - "code": "amplitude.getInstance().init(APIKEY, null, {\n headers: {\n 'x-session-id': appToken,\n \t'Content-Type': 'application/json;charset=utf-8'\n }\n});\n", - "language": "javascript" - } - ] -} -[/block] - -### Logging Events to Multiple Projects - -If you want to log events to multiple Amplitude projects, then you will need to have separate instances for each Amplitude project. As mentioned earlier, each instance will allow for completely independent apiKeys, userIds, deviceIds, and settings. - -You will need to assign a name to each Amplitude project/instance and use that name consistently when fetching that instance to call functions. - -!!!important - Once you have chosen a name for that instance you cannot change it. - -Choose your instance names wisely because every instance's data and settings are tied to its name, and you will need to continue using that instance name for all future versions of your project to maintain data continuity. These names do not need to be the names of your projects in the Amplitude platform, but they will need to remain consistent throughout your code. You also need to be sure that each instance is initialized with the correct apiKey. - -Instance names must be non-null and non-empty strings. Names are case insensitive, and you can fetch each instance name by calling. - -Each new instance created will have its own apiKey, userId, deviceId, and settings. - -The following is an example of how to set up and log events to two separate projects: -[block:code] -{ - "codes": [ - { - "code": "// existing project, existing settings, and existing API key\namplitude.getInstance().init('12345', null, {batchEvents: true});\n// new project, new API key\namplitude.getInstance('new_project').init('67890', null, {includeReferrer: true});\n\n// need to reconfigure new project\namplitude.getInstance('new_project').setUserId('joe@gmail.com');\namplitude.getInstance('new_project').setUserProperties({'gender':'male'});\namplitude.getInstance('new_project').logEvent('Clicked');\n\nvar identify = new amplitude.Identify().add('karma', 1);\namplitude.getInstance().identify(identify);\namplitude.getInstance().logEvent('Viewed Home Page');", - "language": "javascript" - } - ] -} -[/block] - -### Web Attribution - -While Amplitude’s Javascript SDK does not collect web attribution data by default, setting it up is simple. The SDK can automatically collect this information if certain attribution configuration options are enabled. - -Amplitude supports automatically tracking the following through the SDK configuration options: - -- The 5 standard UTM parameters from the user's browser cookie or URL parameters by using `includeUtm`. -- The referring URL and domain from includeReferrer. -- Google Click Identifier from URL parameters through `includeGclid`. -- Facebook Click Identifier from URL parameters through `includeFbclid`. - -#### Track UTM Parameters - -UTM parameters stand for Urchin Traffic Monitor parameters and are useful for analyzing the effectiveness of different ad campaigns and referring sites. Note that UTM parameters are case sensitive so they will turn out to be different values if the capitalization varies. - -There are five different standard UTM parameters: - -- **utm_source:** This identifies which website sent the traffic (e.g. Google, Facebook). -- **utm_medium:** This identifies what type of link was used (e.g. banner, button, email). -- **utm_campaign:** This identifies a specific campaign used (e.g. summer_sale). -- **utm_term:** This identifies paid search terms used (e.g. product+analytics). -- **utm_content:** This identifies what brought the user to the site and is commonly used for A/B testing (e.g. bannerlink, textlink). - -Here is an example URL: - -```bash -https://www.amplitude.com/?utm_source=newsletter&utm_campaign=product_analytics_playbook&utm_medium=email&utm_term=product%20analytics&utm_content=bannerlink -``` - -#### Enabling via SDK - -In Amplitude, once you set the `includeUtm` option to true, the JavaScript SDK will automatically pull UTM parameters from the referring URL and include them as user properties on all of the relevant events: - -- **includeGclid:** Gclid (Google Click Identifier) is a globally unique tracking parameter used by Google. If utilized, Google will append a unique parameter (e.g. "?gclid=734fsdf3") to URLs at runtime. By setting this to true, the SDK will capture `initial_glid` and `gclid` as user properties. -- **includeFbclid:** Fbclid (Facebook Click Identifier) is a globally unique tracking parameter used by Facebook. If utilized, Facebook will append a unique parameter (e.g. "?fbclid=392foih3") to URLs at runtime. By setting this to true, the SDK will capture `initial_fblid` and `fbclid` as user properties. -- **includeUtm:** If true, finds the standard UTM parameters from either the URL or the browser cookie and sets them as user properties. This will set `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, and `utm_content` as well as `initial_utm_source`, `initial_utm_medium`, `initial_utm_campaign`, `initial_utm_term`, and `initial_utm_content` as user properties for the user. -UTM parameters are captured once per session by default and occurs when the user loads your site and the Amplitude SDK for the first time. You can disable the once per session restriction through the saveParamsReferrerOncePerSession configuration option. When the SDK detects that it should start a new session, it will pull the UTM parameters that are available at the time. Those UTM parameters will be set as user properties which will persist for all of the user's events going forward. However, initial UTM parameters are captured only once for each user via a setOnce operation. See the Javascript SDK Configuration Options for reference. - -#### Track Referrers - -If you want to track how users are getting to your website, then all you need to do is track the referrer (the referring site). - -Here are the fields Amplitude supports tracking automatically: - -- **referrer:** The last page the user was on (e.g. ). -- **referring_domain:** The domain that the user was last on (e.g. amplitude.com). - -#### Enabling via SDK - -Once you set the `includeReferrer` option to `true`, Amplitude will capture the referrer and referring_domain for each session and set them as user properties on all of the relevant events: - -- **includeReferrer:** If true, captures the `referrer` and `referring_domain` for each session as user properties as well as the 'initial_referrer' and 'initial_referring_domain' user properties once for each user. The referrer is the entire URL while the referring_domain is only the domain name from where the user came from. - -Initial referring information is captured only once for each user via a setOnce operation. See the Javascript SDK Configuration Options for reference. - -#### First-Touch Attribution - -Amplitude can capture the initial UTM parameters and referrer information for each user. The first-touch attribution values are set when a user's non-null UTM parameters are seen for the first time. The following user properties are set once: - -- initial_utm_source -- initial_utm_medium -- initial_utm_campaign -- initial_utm_term -- initial_utm_content -- initial_referrer -- initial_referring_domain -- initial_gclid -- initial_fbclid - -This is done by setting the JavaScript SDK configuration options `includeReferrer`, `includeUtm`, and `includeGclid` to `true`. - -*Note: Initial attribution information for users can change if there are merged users.* - -#### Last-Touch Attribution - -In addition to first-touch attribution, Amplitude will capture where a user came from for each of their sessions. This is accomplished by setting the following user properties: - -- utm_source -- utm_medium -- utm_campaign -- utm_term -- utm_content -- referrer -- referring_domain -- gclid -- fbclid - -This is done by setting the JavaScript SDK configuration options `includeReferrer`, `includeUtm`, and `includeGclid` to `true`. By default, the SDK will only save values at the start of the session so if a user triggers some flow that causes them to land on the site again with a different set of UTM parameters within the same session, that second set will not be saved. - -#### Multi-Touch Attribution - -If you set `saveParamsReferrerOncePerSession` to `false` in your JavaScript SDK configuration, the SDK will always capture any new values from the user. This will update the following user properties throughout a session if they change: - -- utm_source -- utm_medium -- utm_campaign -- utm_term -- utm_content -- referrer -- referring_domain -- gclid -- fbclid - -Some customers also instrument these user properties as arrays in order to keep track of all the attribution parameters seen within the same session for a single user. - -#### Logging Captured Attribution Values via Amplitude (Advanced Use Case) - -**These events will count towards your event quota**. - -If you set `logAttributionCapturedEvent` to `true` in your JavaScript SDK configuration, the SDK will log an Amplitude event anytime new attribution values are captured from the user. - -**Event Name:** [Amplitude] Attribution Captured - -**Event Properties:** - -- utm_source -- utm_medium -- utm_campaign -- utm_term -- utm_content -- referrer -- referring_domain -- gclid -- fbclid - -### Google Tag Manager - -Amplitude's JavaScript SDK supports integration with Google Tag Manager. Take a look at our demo application for instructions on how to set it up. - -### Dynamic Configuration - -Starting from version 8.9.0, Javascript SDK allows users to configure their apps to use [dynamic configuration](https://developers.amplitude.com/docs/dynamic-configuration). This feature will find the best server url automatically based on app users' geo location. - -- If you have your own proxy server and use custom apiEndPoint, please leave this OFF. -- If you have users in China Mainland, we suggest you turn this on. -- By default, this feature is OFF. So you need to explicitly set it to ON to use it. -- By default, this feature returns server url for Amplitude's US servers, if you need to send data to Amplitude's EU servers, please use setServerZone to set it to EU zone. -[block:code] -{ - "codes": [ - { - "code": "amplitude.getInstance().init(euApiKey, null, {\n useDynamicConfig: true,\n});", - "language": "javascript" - } - ] -} -[/block] - -[block:embed] -{ - "html": false, - "url": "https://github.com/amplitude/GTM-Web-Demo", - "title": "amplitude/GTM-Web-Demo", - "favicon": "https://github.com/favicon.ico", - "image": "https://opengraph.githubassets.com/fd3fddb5a205dca6eec9425063d94b46b10bcb092917ffa9f3e16bff2befc94e/amplitude/GTM-Web-Demo" -} -[/block] diff --git a/includes/group-identify-considerations.md b/includes/group-identify-considerations.md new file mode 100644 index 000000000..1976cb9c3 --- /dev/null +++ b/includes/group-identify-considerations.md @@ -0,0 +1,6 @@ +Use the Group Identify API to set or update properties of particular groups. Keep these considerations in mind: + +- Updates affect only future events, and don't update historical events. +- You can track up to 5 unique group types and 10 total groups. + +The `groupIdentify` method accepts a group type string parameter and group name object parameter, and an Identify object that's applied to the group. \ No newline at end of file diff --git a/includes/logged-out-and-anonymous-users.md b/includes/logged-out-and-anonymous-users.md new file mode 100644 index 000000000..1e0f30669 --- /dev/null +++ b/includes/logged-out-and-anonymous-users.md @@ -0,0 +1,9 @@ +Amplitude [merges user data](https://help.amplitude.com/hc/en-us/articles/115003135607#h_c323d7e5-4662-4a36-b0a1-5110a341e80c), so any events associated with a known `userId` or `deviceId` are linked the existing user. + If a user logs out, Amplitude can merge that user's logged-out events to the user's record. You can change this behavior and log those events to an anonymous user instead. + +To log events to an anonymous user: + +1. Set the `userId` to null. +2. Generate a new `deviceId`. + +Events coming from the current user or device appear as a new user in Amplitude. Note: If you do this, you can't see that the two users were using the same device. \ No newline at end of file diff --git a/includes/track-revenue-properties-table.md b/includes/track-revenue-properties-table.md new file mode 100644 index 000000000..16310ddec --- /dev/null +++ b/includes/track-revenue-properties-table.md @@ -0,0 +1,9 @@ +|
Name
| Description | +| --- | --- | +| `productId` | Optional. String. An identifier for the product. Amplitude recommends something like the "Google Play Store product ID". Defaults to `null`. | +| `quantity`| Required. Integer. The quantity of products purchased. Note: revenue = quantity * price. Defaults to 1. | +| `price` | Required. Double. The price of the products purchased, and this can be negative. Note: revenue = quantity * price. Defaults to `null`.| +| `revenueType` | Optional, but required for revenue verification. String. The type of revenue (e.g. tax, refund, income). Defaults to `null`. | +| `receipt` | Optional. String. The type of revenue (e.g. tax, refund, income). Defaults to `null` | +| `receiptSignature` | Optional, but required for revenue verification. The type of revenue (e.g. tax, refund, income). | null | +| `eventProperties`| Optional. JSONObject. An object of event properties to include in the revenue event. Defaults to `null`. | \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml index 8a12ed111..0b0d75aea 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -131,7 +131,7 @@ nav: - analytics/apis/user-privacy-api.md - Amplitude SDKs: - analytics/sdks/android-sdk.md - - analytics/sdks/sdk-javascript-overview.md + - analytics/sdks/javascript-sdk.md - Experiment: - experiment/index.md - Data: diff --git a/vale/styles/Vocab/dev/reject.txt b/vale/styles/Vocab/dev/reject.txt new file mode 100644 index 000000000..5e97e12d7 --- /dev/null +++ b/vale/styles/Vocab/dev/reject.txt @@ -0,0 +1 @@ +amplitude \ No newline at end of file From f87c9fea95da5d4d421de47bc58dccae3c9d74b0 Mon Sep 17 00:00:00 2001 From: caseyamp Date: Fri, 11 Mar 2022 14:06:58 -0800 Subject: [PATCH 02/13] More small changes, committing for the weekend' --- docs/analytics/sdks/javascript-sdk.md | 63 ++++++++++++++++----------- 1 file changed, 37 insertions(+), 26 deletions(-) diff --git a/docs/analytics/sdks/javascript-sdk.md b/docs/analytics/sdks/javascript-sdk.md index 454b56236..91aab79e6 100644 --- a/docs/analytics/sdks/javascript-sdk.md +++ b/docs/analytics/sdks/javascript-sdk.md @@ -436,7 +436,7 @@ amplitude.getInstance().logEvent('Viewed Home Page'); ### Web Attribution -While Amplitude’s Javascript SDK doesn't collect web attribution data by default, setting it up is simple. The SDK can automatically collect this information if certain attribution configuration options are enabled. +While Amplitude’s JavaScript SDK doesn't collect web attribution data by default, setting it up is simple. The SDK can automatically collect this information if certain attribution configuration options are enabled. Amplitude supports automatically tracking the following through the SDK configuration options: @@ -452,11 +452,11 @@ UTM parameters stand for Urchin Traffic Monitor parameters and are useful for an There are five different standard UTM parameters: -- `utm_source`: This identifies which website sent the traffic (e.g. Google, Facebook). -- `utm_medium`: This identifies what type of link was used (e.g. banner, button, email). -- `utm_campaign`: This identifies a specific campaign used (e.g. summer_sale). -- `utm_term`: This identifies paid search terms used (e.g. product+analytics). -- `utm_content`: This identifies what brought the user to the site and is commonly used for A/B testing (e.g. bannerlink, textlink). +- `utm_source`: This identifies which website sent the traffic (for example: Google, Facebook). +- `utm_medium`: This identifies what type of link was used (for example: banner, button, email). +- `utm_campaign`: This identifies a specific campaign used (for example: summer_sale). +- `utm_term`: This identifies paid search terms used (for example: product+analytics). +- `utm_content`: This identifies what brought the user to the site and is commonly used for A/B testing (for example: bannerlink, textlink). Here is an example URL: @@ -466,19 +466,19 @@ Here is an example URL: In Amplitude, after you set the `includeUtm` option to true, the JavaScript SDK automatically pulls UTM parameters from the referring URL and include them as user properties on all relevant events: -- **includeGclid:** Gclid (Google Click Identifier) is a globally unique tracking parameter used by Google. If utilized, Google will append a unique parameter (e.g. "?gclid=734fsdf3") to URLs at runtime. By setting this to true, the SDK captures `initial_glid` and `gclid` as user properties. -- **includeFbclid:** Fbclid (Facebook Click Identifier) is a globally unique tracking parameter used by Facebook. If utilized, Facebook will append a unique parameter (e.g. "?fbclid=392foih3") to URLs at runtime. By setting this to true, the SDK captures `initial_fblid` and `fbclid` as user properties. -- **includeUtm:** If true, finds the standard UTM parameters from either the URL or the browser cookie and sets them as user properties. This sets `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, and `utm_content` as well as `initial_utm_source`, `initial_utm_medium`, `initial_utm_campaign`, `initial_utm_term`, and `initial_utm_content` as user properties for the user. -UTM parameters are captured once per session by default and occurs when the user loads your site and the Amplitude SDK for the first time. You can disable the once per session restriction through the saveParamsReferrerOncePerSession configuration option. When the SDK detects that it should start a new session, it pulls the UTM parameters that are available at the time. Those UTM parameters will be set as user properties which persists for all of the user's events going forward. However, initial UTM parameters are captured only once for each user via a setOnce operation. +- `includeGclid`: Gclid (Google Click Identifier) is a globally unique tracking parameter used by Google. If utilized, Google will append a unique parameter (for example: `"?gclid=734fsdf3"`) to URLs at runtime. By setting this to true, the SDK captures `initial_glid` and `gclid` as user properties. +- `includeFbclid`: Fbclid (Facebook Click Identifier) is a globally unique tracking parameter used by Facebook. If utilized, Facebook will append a unique parameter (for example: `"?fbclid=392foih3"`) to URLs at runtime. By setting this to true, the SDK captures `initial_fblid` and `fbclid` as user properties. +- `includeUtm`: If true, finds the standard UTM parameters from either the URL or the browser cookie and sets them as user properties. This sets `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, and `utm_content` as well as `initial_utm_source`, `initial_utm_medium`, `initial_utm_campaign`, `initial_utm_term`, and `initial_utm_content` as user properties for the user. +UTM parameters are captured once per session by default and occurs when the user loads your site and the Amplitude SDK for the first time. You can disable the once per session restriction through the `saveParamsReferrerOncePerSession` configuration option. When the SDK detects that it should start a new session, it pulls the UTM parameters that are available at the time. Those UTM parameters are set as user properties which persists for all of the user's events going forward. However, initial UTM parameters are captured only once for each user via a setOnce operation. #### Track Referrers -If you want to track how users are getting to your website, then all you need to do is track the referrer (the referring site). +If you want to track how users are getting to your website, then track the referrer (the referring site). -Here are the fields Amplitude supports tracking automatically: +Amplitude supports tracking these fields automatically: -- `referrer`: The last page the user was on (e.g. ). -- `referring_domain`: The domain that the user was last on (e.g. amplitude.com). +- `referrer`: The last page the user was on (for example, ``). +- `referring_domain`: The domain that the user was last on (for example, `amplitude.com`). #### Enabling via SDK @@ -506,7 +506,7 @@ Amplitude can capture the initial UTM parameters and referrer information for ea This is done by setting the JavaScript SDK configuration options `includeReferrer`, `includeUtm`, and `includeGclid` to `true`. !!!note - Initial attribution information for users can change if they are merged with another user. + Initial attribution information for users can change if they're merged with another user. #### Last-Touch Attribution @@ -522,7 +522,8 @@ In addition to first-touch attribution, Amplitude will capture where a user came - `gclid` - `fbclid` -This is done by setting the JavaScript SDK configuration options `includeReferrer`, `includeUtm`, and `includeGclid` to `true`. By default, the SDK will only save values at the start of the session so if a user triggers some flow that causes them to land on the site again with a different set of UTM parameters within the same session, that second set will not be saved. +This is done by setting the JavaScript SDK configuration options `includeReferrer`, `includeUtm`, and `includeGclid` to `true`. + By default, the SDK only saves values at the start of the session so if a user triggers some flow that causes them to land on the site again with a different set of UTM parameters within the same session, that second set isn't saved. #### Multi-Touch Attribution @@ -620,11 +621,11 @@ The cookie is used to keep track of a few bits of metadata for the SDK: #### Disabling Cookies -Amplitude cookies can be disabled altogether using the `disableCookies` option. When you disable cookies, the JavaScript SDK will fallback to using `localStorage` to store its data. LocalStorage is a great alternative, but there is one small potential downside. If you track anonymous users across subdomains of your product (eg: `www.amplitude.com` vs `analytics.amplitude.com`), this doesn't work. Access to localStorage is restricted by subdomain. +Amplitude cookies can be disabled altogether using the `disableCookies` option. When you disable cookies, the JavaScript SDK will fallback to using `localStorage` to store its data. LocalStorage is a great alternative, but there is one small potential downside. If you track anonymous users across subdomains of your product (for example: `www.amplitude.com` vs `analytics.amplitude.com`), this doesn't work. Access to localStorage is restricted by subdomain. #### SameSite -The JavaScript SDK defaults to setting the SameSite option on its cookies to `None`. This can be overridden with the `sameSiteCookie` option. We set the option to `Lax` option on our own sites at amplitude. Lax is recommended unless there are instances where you have third party sites that `POST` forms to your site. The default may change to `Lax` in the future. +The JavaScript SDK defaults to setting the SameSite option on its cookies to `None`. This can be overridden with the `sameSiteCookie` option. We set the option to `Lax` option on our own sites at Amplitude. Lax is recommended unless there are instances where you have third party sites that `POST` forms to your site. The default may change to `Lax` in the future. #### HttpOnly Cookies @@ -683,26 +684,34 @@ You can track anonymous behavior across two different domains. Anonymous users a Users who start on Site 1 and then navigate to Site 2 will need to have the Device ID generated from Site 1 passed as a parameter to Site 2. Site 2 then needs to initialize the SDK with that Device ID. The SDK can parse the URL parameter automatically if `deviceIdFromUrlParam` is enabled. - From Site 1, grab the Device ID from `amplitude.getInstance().options.deviceId`. -- Pass the Device ID to Site 2 via a URL parameter when the user navigates. (e.g. `www.example.com?amp_device_id=device_id_from_site_1`) +- Pass the Device ID to Site 2 via a URL parameter when the user navigates. (for example: `www.example.com?amp_device_id=device_id_from_site_1`) - Initialize the Amplitude SDK on Site 2 with `amplitude.init('API_KEY', null, {deviceIdFromUrlParam: true})`. ### Tracking UTM Parameters, Referrer, and gclid (JavaScript) Amplitude supports automatically tracking: -- Standard UTM parameters from the user's cookie or URL parameters when the configuration option includeUtm is set to true during initialization. +- Standard UTM parameters from the user's cookie or URL parameters when the configuration option `includeUtm` is set to true during initialization. - The referring URL when the configuration option includeReferrer is set to true during initialization. -- gclid (Google Click ID) from URL parameters when the configuration option includeGclid is set to true during initialization. +- `gclid` (Google Click ID) from URL parameters when the configuration option includeGclid is set to true during initialization. -If tracking is enabled, then the SDK will set the values as user properties (e.g. referrer or utm_source) once per session (this is last touch attribution). The SDK will also save the initial values using a setOnce operation (e.g. initial_referrer or initial_utm_source), and once set that value will never change (this is first touch attribution). +If tracking is enabled, then the SDK sets the values as user properties (for example, `referrer` or `utm_source`) once per session. This is known as last touch attribution. + The SDK also saves the initial values like `initial_referrer` and `initial_utm_source` using a `setOnce` operation. + When these values are set, they never change. This is known as first touch attribution. -*Note: By default, the SDK will only save the values at the start of the session.* For example, if a user lands on your site with an initial set of UTM parameters and triggers some flow that causes them to land on your site again with a different set of UTM parameters within the same Amplitude session, then that second set isn't saved. You can set the configuration option saveParamsReferrerOncePerSession to false to remove that restriction so that the SDK will always capture any new values from the user. +!!!note "`saveParamsReferrerOncePerSession`" + By default, the SDK only saves the values at the start of the session. For example, if a user lands on your site with an initial set of UTM parameters and triggers some flow that causes them + to land on your site again with a different set of UTM parameters within the same Amplitude session, the second set isn't saved. + You can set the configuration option `saveParamsReferrerOncePerSession` to `false` to remove that restriction so that the SDK always captures new values from the user. -*Note: By default, the SDK will carry over existing UTM Parameters and Referrer values at the start of a new session.* For example, if a users session expires, the SDK will map the user's Referrer and UTM Parameters to existing values. *To reset those values to null upon instantiating a new session, set unsetParamsReferrerOnNewSession to true.* +!!!note "`unsetParamsReferrerOnNewSession`" + By default, the SDK carries over existing UTM Parameters and Referrer values at the start of a new session. For example, if a users session expires, the SDK maps the user's Referrer and UTM Parameters to existing values.  + To reset those values to null upon instantiating a new session, set `unsetParamsReferrerOnNewSession` to `true`. ### Callbacks for logEvent, Identify, and Redirect -You can pass a callback function to logEvent and identify, which will get called after receiving a response from the server. This is useful if timing may cause an event to not be captured before the browser navigates away from a webpage. Putting the navigation in a callback to the logEvent method will guarantee the event is captured before the navigation occurs. Here is a logEvent example: +You can pass a callback function to `logEvent` and identify, which gets called after receiving a response from the server. This is useful if timing may cause an event to not be captured before the browser navigates away from a webpage. + Putting the navigation in a callback to the logEvent method will guarantee the event is captured before the navigation occurs. Here is a logEvent example: ```js amplitude.getInstance().logEvent("EVENT_TYPE", null, callback_function); @@ -742,7 +751,9 @@ var trackClickLinkA = function() { }; ``` -In the case that optOut is true, then no event is logged but the callback will be called. In the case that batchEvents is true, if the batch requirements eventUploadThreshold and eventUploadPeriodMillis aren't met when logEvent is called, then no request is sent but the callback is still called. In these cases, the callback will be called with an input status of 0 and a response of 'No request sent'. +In the case that `optOut` is `true`, then no event is logged but the callback is called. + In the case that `batchEvents` is `true`, if the batch requirements `eventUploadThreshold` and `eventUploadPeriodMillis` aren't met when `logEvent` is called, then no request is sent but the callback is still called. + In these cases, the callback is called with an input status of 0 and a response of 'No request sent'. ### Error Callbacks From 778047730d4068254ea4770f6e976c4fb76969cc Mon Sep 17 00:00:00 2001 From: caseyamp Date: Mon, 14 Mar 2022 12:43:39 -0700 Subject: [PATCH 03/13] javascript SDK cleanup. Minor changes to android sdk' --- docs/analytics/sdks/android-sdk.md | 9 +- docs/analytics/sdks/javascript-sdk.md | 210 +++++++++++++++----------- includes/abbreviations.md | 4 +- vale/styles/write-good/ThereIs.yml | 6 - vale/styles/write-good/TooWordy.yml | 1 - 5 files changed, 134 insertions(+), 96 deletions(-) delete mode 100644 vale/styles/write-good/ThereIs.yml diff --git a/docs/analytics/sdks/android-sdk.md b/docs/analytics/sdks/android-sdk.md index 2ee45028b..d24bf1093 100644 --- a/docs/analytics/sdks/android-sdk.md +++ b/docs/analytics/sdks/android-sdk.md @@ -964,10 +964,11 @@ Second, add the following code in your root activity's onCreate life cycle. Android SDK allows users to configure their apps to use [dynamic configuration](https://developers.amplitude.com/docs/dynamic-configuration). This feature finds the best server URL automatically based on app users' location. -- If you have your own proxy server and use `setServerUrl` API, leave dynamic configuration OFF. -- If you have users in China Mainland, we suggest you turn this on. -- By default, this feature is OFF. You must explicitly set it to ON to use it. -- By default, this feature returns server URL for Amplitude's US servers, if you need to send data to Amplitude's EU servers, please use `setServerZone` to set it to EU zone. +- If you have your own proxy server and use `setServerUrl` API, leave dynamic configuration off. +- If you have users in China Mainland, then we recommend using dynamic configuration. +- By default, this feature returns server URL of Amplitude's US servers, if you need to send data to Amplitude's EU servers, use `setServerZone` to set it to EU zone. + + To use, set `setUseDynamicConfig` to `true`. === "Java" diff --git a/docs/analytics/sdks/javascript-sdk.md b/docs/analytics/sdks/javascript-sdk.md index 91aab79e6..4b991b153 100644 --- a/docs/analytics/sdks/javascript-sdk.md +++ b/docs/analytics/sdks/javascript-sdk.md @@ -15,12 +15,12 @@ This is the official documentation for the Amplitude JavaScript SDK. --8<-- "includes/ampli-vs-amplitude.md" -## SDK Installation +## SDK installation -### Installing Via the Snippet +### Installing via the Snippet You can install the JavaScript SDK using a small snippet of code which you paste on your site to asynchronously load the SDK. - On every page that you want to install Amplitude analytics, paste the code snippet just before the `` tag, replacing API_KEY with the API Key given to you. + On every page that you want to install Amplitude analytics, paste the code snippet just before the `` tag, replacing API_KEY with your project's API key. You can find your project's API Key in your project's [Settings page](https://help.amplitude.com/hc/en-us/articles/360058073772). ```js @@ -69,7 +69,7 @@ If you are using yarn, use the following command: yarn add amplitude-js ``` -Now, import amplitude into your project: +Now, import `amplitude` into your project: ```js import amplitude from 'amplitude-js'; @@ -87,16 +87,16 @@ var instance1 = amplitude.getInstance().init("API_KEY"); // initializes default var instance2 = amplitude.getInstance("instance-name").init("API_KEY"); // initializes named instance of Amplitude client ``` -#### Initialization with Options +#### Initialization with options -Custom options can be passed into the `init` method. See a [list of options](https://github.com/amplitude/Amplitude-JavaScript/blob/main/src/options.js) on GitHub. +Pass custom options in the `init` method. See a [list of options](https://github.com/amplitude/Amplitude-JavaScript/blob/main/src/options.js) on GitHub. ```js var options = {}; var instance = amplitude.getInstance("instance").init("API_KEY", null, options); // initializes with the given options ``` -### Setting User Id +### Set `userID` Set `userID` when initializing the client, or after initialization with the `setUserId` method. @@ -114,15 +114,15 @@ Set `userID` when initializing the client, or after initialization with the `set amplitude.getInstance().setUserId(userId); ``` -### EU Data Residency +### EU data residency Beginning with version 8.9.0, you can configure the server zone after initializing the client for sending data to Amplitude's EU servers. The SDK sends data based on the server zone if it's set. The server zone config supports dynamic configuration as well. -For previous versions, you need to configure the `apiEndpoint` property after initializing the client. +For earlier versions, you need to configure the `apiEndpoint` property after initializing the client. !!!note - For EU data residency, the project must be set up inside Amplitude EU. You must initialize the SDK with the API key from Amplitude EU. + For EU data residency, set up the project inside Amplitude EU. You must initialize the SDK with the API key from Amplitude EU. ```js // For versions starting from 8.9.0 @@ -138,9 +138,9 @@ amplitude.getInstance().init(euApiKey, null, { }); ``` -### Sending Events +### Sending events -#### Basic Events +#### Basic events Events represent how users interact with your application. For example, “Button Clicked” may be an action you want to note. @@ -149,9 +149,9 @@ var event = “Button Clicked”; amplitude.getInstance().logEvent(event); ``` -#### Events with Properties +#### Events with properties -Events can also contain properties. They provide context about the event taken. For example, “hover time” may be a relevant event property to “Button Clicked”. +Events can also contain properties. They give context about the event taken. For example, “hover time” may be a relevant event property to “Button Clicked”. ```js var event = “Button Clicked”; @@ -178,14 +178,14 @@ var eventProperties2 = { amplitude.getInstance().logEvent(event, eventProperties2); ``` -### User Properties +### User properties User properties help you understand your users at the time they performed some action within your app such as their device details, their preferences, or language. -#### Setting a User Property +#### Setting a user property -The amplitude Identify object provides controls over setting user properties. - An Identify object must first be instantiated, then Identify methods can be called on it, and finally the client makes a call with the Identify object +The Amplitude Identify object provides controls over setting user properties. + First, an Identify object must be instantiated, then you can call Identify methods on it, and finally the client makes a call with the Identify object. ```js new amplitude.Identify(); // does nothing, must call one of the following methods and pass to client @@ -207,7 +207,7 @@ amplitude.getInstance().identify(identify2); #### setOnce -`setOnce` sets the value of a user property only once. Subsequent calls using `setOnce` will be ignored. +`setOnce` sets the value of a user property only once. Later calls using `setOnce` are ignored. ```js var identify = new amplitude.Identify().setOnce('key1', 'value1'); @@ -216,7 +216,7 @@ amplitude.getInstance().identify(identify); #### add -`add` increments a user property by some numerical value. If the user property doesn't have a value set yet, it will be initialized to `0` before being incremented. +`add` increments a user property by some numerical value. If the user property doesn't have a value set yet, it's initialized to `0` before being incremented. ```js var identify = new amplitude.Identify().add('value1', 10); @@ -224,9 +224,10 @@ amplitude.getInstance().identify(identify); ``` -#### Setting Multiple User Properties +#### Setting multiple user properties -You can use `setUserProperties` as a shorthand to set multiple user properties at one time. This method is simply a wrapper around `Identify.set` and `identify`. For example, a user's city can be set with the following code. +You can use `setUserProperties` as a shorthand to set multiple user properties at one time. This method is a wrapper around `Identify.set` and `identify`. + For example, set a user's city with this code: ```js var userProperties = { @@ -235,7 +236,7 @@ var userProperties = { amplitude.getInstance().setUserProperties(userProperties); ``` -#### Arrays in User Properties +#### Arrays in user properties Arrays can be used as user properties. You can directly set arrays or use `append` to generate an array. @@ -245,14 +246,15 @@ var identify = new amplitude.Identify().set('key1', values); amplitude.getInstance().identify(identify); ``` -#### prepend/append +#### `prepend` and `append` - `append` will append a value or values to a user property array. - `prepend` will prepend a value or values to a user property. -If the user property doesn't have a value set yet, it will be initialized to an empty list before the new values are added. If the user property has an existing value and it's not a list, it will be converted into a list with the new value added. +If the user property doesn't have a value set yet, it's initialized to an empty list before the new values are added. + If the user property has an existing value and it's not a list, it's converted into a list with the new value added. -### User Groups +### User groups --8<-- "includes/editions-growth-enterprise-with-accounts.md" @@ -266,7 +268,8 @@ If the user property doesn't have a value set yet, it will be initialized to an amplitude.getInstance().setGroup('orgId', '[10,16]'); ``` -You can also use `logEventWithGroups` to set event-level groups, meaning the group designation only applies for the specific event being logged and doesn't persist on the user unless you explicitly set it with `setGroup`. +You can also use `logEventWithGroups` to set event-level groups, meaning the group designation only applies for the specific event being logged and doesn't persist on the user unless you explicitly + set it with `setGroup`. ```js var eventProperties = { @@ -276,7 +279,7 @@ var eventProperties = { amplitude.getInstance().logEventWithGroups('initialize_game', eventProperties, {'sport': 'soccer'}); ``` -### Group Identify +### Group identify --8<-- "includes/editions-growth-enterprise-with-accounts.md" @@ -294,7 +297,10 @@ An optional callback function can be supplied as a fourth argument to `groupIden ### Track Revenue -The preferred method of tracking revenue for a user is to use `logRevenueV2()` in conjunction with the provided Revenue interface. Revenue instances will store each revenue transaction and allow you to define several special revenue properties (such as 'revenueType', 'productIdentifier', etc.) that are used in Amplitude's Event Segmentation and Revenue LTV charts. You can also add event properties to revenue events via the eventProperties field. These Revenue instance objects are then passed into `logRevenueV2` to send as revenue events to Amplitude. This allows us to automatically display data relevant to revenue in the platform. You can use this to track both in-app and non-in-app purchases. +The preferred method of tracking revenue for a user is to use `logRevenueV2()` in conjunction with the provided Revenue interface. + Revenue instances store each revenue transaction and let you define several special revenue properties that are used in Amplitude's Event Segmentation and Revenue LTV charts, such as `revenueType` and `productIdentifier`. + You can also add event properties to revenue events via the eventProperties field. These Revenue instance objects are then passed into `logRevenueV2` to send as revenue events to Amplitude. + This allows Amplitude to automatically display data relevant to revenue in the platform. You can use this to track both in-app and non-in-app purchases. To track revenue from a user, call logRevenueV2() each time a user generates revenue. Here is an example: @@ -303,18 +309,19 @@ var revenue = new amplitude.Revenue().setProductId('com.company.productId').setP amplitude.getInstance().logRevenueV2(revenue); ``` -Calling `logRevenueV2` will generate a revenue event type: +Calling `logRevenueV2` generates a revenue event type: -- **'[Amplitude] Revenue':** This event is logged for all revenue events, regardless of whether or not verification is turned on. +- [Amplitude] Revenue: This event is logged for all revenue events, regardless of whether verification is enabled. -You can't change the default names given to these client-side revenue events in the raw data but you do have the option to modify the [display name](https://amplitude.zendesk.com/hc/en-us/articles/235649848#events). To learn more about tracking revenue, see our documentation [here](https://amplitude.zendesk.com/hc/en-us/articles/115003116888). +You can't change the default names given to these client-side revenue events in the raw data but you do have the option to change the [display name](https://help.amplitude.com/hc/en-us/articles/235649848#events). + To learn more about tracking revenue, see the documentation [here](https://help.amplitude.com/hc/en-us/articles/115003116888). !!!note Amplitude doesn't support currency conversion. All revenue data should be normalized to your currency of choice, before being sent to Amplitude. --8<-- "includes/track-revenue-properties-table.md" -### Opt Out of Tracking +### Opt users out of tracking You can turn off logging for a given user by calling `setOptOut`: @@ -328,9 +335,10 @@ No events are saved or sent to the server while `setOptOut` is enabled. The opt amplitude.getInstance().setOptOut(false); ``` -### Disable Tracking +### Disable tracking -By default, the JavaScript SDK tracks a number of properties automatically. You can override this behavior by passing an object called `trackingOptions` when initializing the SDK, setting the appropriate options to `false`. These options are listed below: +By default, the JavaScript SDK tracks some properties automatically. You can override this behavior by passing an object called `trackingOptions` when initializing the SDK, + setting the appropriate options to `false`. |
Parameter
| Default Value| |-------|------------| @@ -349,7 +357,9 @@ By default, the JavaScript SDK tracks a number of properties automatically. You |`version_name` | `true`| !!!warning - The *trackingOptions* configurations only prevent default properties from being tracked on new projects, with no existing data. If you have a project with existing data that you would like to stop collecting the default properties for, please contact our Support team at support.amplitude.com. Note that the existing data isn't deleted. + The `trackingOptions` configurations only prevent default properties from being tracked on new projects that have no existing data. + If you have a project with existing data that you would like to stop collecting the default properties for, please contact the Support team at support.amplitude.com. + Note that the existing data isn't deleted. ### Setting Custom User ID @@ -365,9 +375,10 @@ You can also add the User ID as an argument to the init call. [[Amplitude] instance] initializeApiKey:@"API_KEY" userId:@"USER_ID"]; ``` -Don't assign users a user ID that could change as each unique user ID is interpreted as a unique user in Amplitude. For more information see [Track unique users in Amplitude](https://help.amplitude.com/hc/en-us/articles/115003135607-Track-unique-users-in-Amplitude) in the Help Center. +Don't assign users a user ID that could change as each unique user ID is interpreted as a unique user in Amplitude. For more information see + [Track unique users in Amplitude](https://help.amplitude.com/hc/en-us/articles/115003135607-Track-unique-users-in-Amplitude) in the Help Center. -### Log Out and Anonymous Users +### Logged out and anonymous users --8<-- "includes/logged-out-and-anonymous-users.md" @@ -378,7 +389,9 @@ amplitude.getInstance().regenerateDeviceId(); ### Session Tracking -Events triggered within 30 minutes of each other are counted towards the current session. The time of the first event marks the start time of a session and the last event triggered marks the end time of a session. You can change the session timeout window via the SDK configuration option field sessionTimeout. +Events triggered within 30 minutes of each other are counted towards the current session. + The time of the first event marks the start time of a session and the last event triggered marks the end time of a session. + You can change the session timeout window via the SDK configuration option field `sessionTimeout`. #### Getting the Session ID @@ -390,7 +403,7 @@ var sessionId = amplitude.getInstance()._sessionId; ### Configuring HTTP Headers -HTTP request headers that are attached to sent events can be set using the `options.headers` configuration when initializing. This should only be relevant if a [domain proxy](https://developers.amplitude.com/docs/domain-proxies) is used that requires custom header options. +If you are using a [domain proxy](https://developers.amplitude.com/docs/domain-proxies) that requires custom HTTP request headers, configure them with `options.headers` during initialization. ```js amplitude.getInstance().init(APIKEY, null, { @@ -403,14 +416,15 @@ amplitude.getInstance().init(APIKEY, null, { ### Logging Events to Multiple Projects -If you want to log events to multiple Amplitude projects, then must have separate instances for each Amplitude project. As mentioned earlier, each instance allows for independent `apiKeys`, `userIds`, `deviceIds`, and settings. +If you want to log events to multiple Amplitude projects, then must have separate instances for each Amplitude project. + Each instance allows for independent `apiKeys`, `userIds`, `deviceIds`, and settings. You must assign a name to each Amplitude project and instance and use that name consistently when fetching that instance to call functions. !!!important After you have chosen a name for that instance you can't change it. - Choose your instance names wisely. Every instance's data and settings are tied to its name, and you must continue using that instance name for all future versions of your project to maintain data continuity. - Instance names don't need be the names of your projects in the Amplitude platform, but they need to remain consistent throughout your code. You also need to be sure that each instance is initialized with the correct `apiKey`. + Choose your instance names carefully. Every instance's data and settings are tied to its name, and you must use that instance name for all future versions of your project to maintain data continuity. + Instance names don't need be the names of your projects in the Amplitude platform, but they need to remain consistent throughout your code. Each instance must also be initialized with the correct `apiKey`. Instance names must be non-null and non-empty strings. Names are case insensitive, and you can fetch each instance name by calling. @@ -436,7 +450,8 @@ amplitude.getInstance().logEvent('Viewed Home Page'); ### Web Attribution -While Amplitude’s JavaScript SDK doesn't collect web attribution data by default, setting it up is simple. The SDK can automatically collect this information if certain attribution configuration options are enabled. +While Amplitude’s JavaScript SDK doesn't collect web attribution data by default, setting it up is simple. + The SDK can automatically collect this information if you enable attribution configuration options. Amplitude supports automatically tracking the following through the SDK configuration options: @@ -453,7 +468,7 @@ UTM parameters stand for Urchin Traffic Monitor parameters and are useful for an There are five different standard UTM parameters: - `utm_source`: This identifies which website sent the traffic (for example: Google, Facebook). -- `utm_medium`: This identifies what type of link was used (for example: banner, button, email). +- `utm_medium`: This identifies the link type that was used (for example: banner, button, email). - `utm_campaign`: This identifies a specific campaign used (for example: summer_sale). - `utm_term`: This identifies paid search terms used (for example: product+analytics). - `utm_content`: This identifies what brought the user to the site and is commonly used for A/B testing (for example: bannerlink, textlink). @@ -462,14 +477,17 @@ Here is an example URL: `https://www.amplitude.com/?utm_source=newsletter&utm_campaign=product_analytics_playbook&utm_medium=email&utm_term=product%20analytics&utm_content=bannerlink` -#### Enabling via SDK +##### Enabling via SDK In Amplitude, after you set the `includeUtm` option to true, the JavaScript SDK automatically pulls UTM parameters from the referring URL and include them as user properties on all relevant events: -- `includeGclid`: Gclid (Google Click Identifier) is a globally unique tracking parameter used by Google. If utilized, Google will append a unique parameter (for example: `"?gclid=734fsdf3"`) to URLs at runtime. By setting this to true, the SDK captures `initial_glid` and `gclid` as user properties. -- `includeFbclid`: Fbclid (Facebook Click Identifier) is a globally unique tracking parameter used by Facebook. If utilized, Facebook will append a unique parameter (for example: `"?fbclid=392foih3"`) to URLs at runtime. By setting this to true, the SDK captures `initial_fblid` and `fbclid` as user properties. +- `includeGclid`: Gclid (Google Click Identifier) is a globally unique tracking parameter used by Google. If utilized, Google appends a unique parameter (for example: `"?gclid=734fsdf3"`) to URLs at runtime. By setting this to true, the SDK captures `initial_glid` and `gclid` as user properties. +- `includeFbclid`: Fbclid (Facebook Click Identifier) is a globally unique tracking parameter used by Facebook. If utilized, Facebook appends a unique parameter (for example: `"?fbclid=392foih3"`) to URLs at runtime. By setting this to true, the SDK captures `initial_fblid` and `fbclid` as user properties. - `includeUtm`: If true, finds the standard UTM parameters from either the URL or the browser cookie and sets them as user properties. This sets `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, and `utm_content` as well as `initial_utm_source`, `initial_utm_medium`, `initial_utm_campaign`, `initial_utm_term`, and `initial_utm_content` as user properties for the user. -UTM parameters are captured once per session by default and occurs when the user loads your site and the Amplitude SDK for the first time. You can disable the once per session restriction through the `saveParamsReferrerOncePerSession` configuration option. When the SDK detects that it should start a new session, it pulls the UTM parameters that are available at the time. Those UTM parameters are set as user properties which persists for all of the user's events going forward. However, initial UTM parameters are captured only once for each user via a setOnce operation. +UTM parameters are captured once per session by default and occurs when the user loads your site and the Amplitude SDK for the first time. + You can disable the once per session restriction through the `saveParamsReferrerOncePerSession` configuration option. When the SDK detects that it should start a new session, + it pulls the UTM parameters that are available at the time. Those UTM parameters are set as user properties which persists for all the user's events going forward. + However, initial UTM parameters are captured only once for each user via a `setOnce` operation. #### Track Referrers @@ -480,18 +498,19 @@ Amplitude supports tracking these fields automatically: - `referrer`: The last page the user was on (for example, ``). - `referring_domain`: The domain that the user was last on (for example, `amplitude.com`). -#### Enabling via SDK +##### Enabling via SDK -Once you set the `includeReferrer` option to `true`, Amplitude captures the `referrer` and `referring_domain` for each session and set them as user properties on relevant events: +After you set the `includeReferrer` option to `true`, Amplitude captures the `referrer` and `referring_domain` for each session and set them as user properties on relevant events: - `includeReferrer`: When `true`, captures the `referrer` and `referring_domain` for each session as user properties as well as the `initial_referrer` and `initial_referring_domain` user properties once for each user. - The referrer is the entire URL while the referring_domain is only the domain name from where the user came from. + The referrer is the entire URL while the `referring_domain` is only the domain name from where the user came from. Initial referring information is captured only once for each user via a `setOnce` operation. #### First-Touch Attribution -Amplitude can capture the initial UTM parameters and referrer information for each user. The first-touch attribution values are set when a user's non-null UTM parameters are seen for the first time. The following user properties are set once: +Amplitude can capture the initial UTM parameters and referrer information for each user. The first-touch attribution values are set when a user's non-null UTM parameters are seen for the first time. + These user properties are set once: - `initial_utm_source` - `initial_utm_medium` @@ -510,7 +529,7 @@ This is done by setting the JavaScript SDK configuration options `includeReferre #### Last-Touch Attribution -In addition to first-touch attribution, Amplitude will capture where a user came from for each of their sessions. This is accomplished by setting the following user properties: +In addition to first-touch attribution, Amplitude captures where a user came from for each of their sessions by setting these user properties: - `utm_source` - `utm_medium` @@ -527,7 +546,7 @@ This is done by setting the JavaScript SDK configuration options `includeReferre #### Multi-Touch Attribution -If you set `saveParamsReferrerOncePerSession` to `false` in your JavaScript SDK configuration, the SDK will always capture any new values from the user. This updates these user properties throughout a session if they change: +If you set `saveParamsReferrerOncePerSession` to `false` in your JavaScript SDK configuration, the SDK always capture any new values from the user. This updates these user properties throughout a session if they change: - `utm_source` - `utm_medium` @@ -565,16 +584,18 @@ If you set `logAttributionCapturedEvent` to `true` in your JavaScript SDK config ### Google Tag Manager -Amplitude's JavaScript SDK supports integration with Google Tag Manager. Take a look at our demo application for instructions on how to set it up. +Amplitude's JavaScript SDK supports integration with Google Tag Manager. See the [demo app](https://github.com/amplitude/GTM-Web-Demo) on GitHub for instructions on how to set it up. ### Dynamic Configuration -Beginning with version 8.9.0, the JavaScript SDK allows users to configure their apps to use [dynamic configuration](https://developers.amplitude.com/docs/dynamic-configuration). This feature finds the best server URL automatically based on app users' location. +Beginning with version 8.9.0, the JavaScript SDK allows users to configure their apps to use [dynamic configuration](https://developers.amplitude.com/docs/dynamic-configuration). + This feature finds the best server URL automatically based on app users' location. -- If you have your own proxy server and use `apiEndPoint` API, leave dynamic configuration OFF. -- If you have users in China Mainland, we suggest you turn this on. -- By default, this feature is OFF. You must explicitly set it to ON to use it. -- By default, this feature returns server URL of Amplitude's US servers, if you need to send data to Amplitude's EU servers, please use `setServerZone` to set it to EU zone. + To use, set `useDynamicConfig` to `true`. + +- If you have your own proxy server and use `apiEndPoint` API, leave dynamic configuration off. +- If you have users in China Mainland, then we recommend using dynamic configuration. +- By default, this feature returns server URL of Amplitude's US servers, if you need to send data to Amplitude's EU servers, use `setServerZone` to set it to EU zone. ```js amplitude.getInstance().init(euApiKey, null, { @@ -589,7 +610,7 @@ amplitude.getInstance().init(euApiKey, null, { You can get a user's current Device ID with the following code: ```js -var deviceId = amplitude.getInstance().options.deviceId; // existing device id +var deviceId = amplitude.getInstance().options.deviceId; // existing device ID ``` ### Setting Configuration Options @@ -609,23 +630,27 @@ amplitude.getInstance().init("API_KEY", null, { #### Cookies Created by the SDK -On initialization, the SDK will create a cookie that begins with the prefix `amp_` and ends with this first six digits of your API key. For example `amplitude.getInstance().init("a2dbce0e18dfe5f8e74493843ff5c053")` would create a cookie with the key `amp_a2dbce`. +On initialization, the SDK creates a cookie that begins with the prefix `amp_` and ends with this first six digits of your API key. + For example, `amplitude.getInstance().init("a2dbce0e18dfe5f8e74493843ff5c053")` would create a cookie with the key `amp_a2dbce`. -The cookie is used to keep track of a few bits of metadata for the SDK: +The cookie is used to keep track of metadata for the SDK: -- A randomly generated device id -- The current session id -- The current user id if a user id is set +- A randomly-generated device ID +- The current session ID +- The current user ID if a user ID is set - The last event time -- A few sequence ids in order to sequence events and identifies correctly +- Sequence IDs to put events and identify operations in the correct order #### Disabling Cookies -Amplitude cookies can be disabled altogether using the `disableCookies` option. When you disable cookies, the JavaScript SDK will fallback to using `localStorage` to store its data. LocalStorage is a great alternative, but there is one small potential downside. If you track anonymous users across subdomains of your product (for example: `www.amplitude.com` vs `analytics.amplitude.com`), this doesn't work. Access to localStorage is restricted by subdomain. +Amplitude cookies can be disabled altogether using the `disableCookies` option. When you disable cookies, the JavaScript SDK defaults to using `localStorage` to store its data. + LocalStorage is a great alternative, but can't track cookies across domains. + Beause access to `localStorage` is restricted by subdomain, you can't track anonymous users across subdomains of your product (for example: `www.amplitude.com` vs `analytics.amplitude.com`). #### SameSite -The JavaScript SDK defaults to setting the SameSite option on its cookies to `None`. This can be overridden with the `sameSiteCookie` option. We set the option to `Lax` option on our own sites at Amplitude. Lax is recommended unless there are instances where you have third party sites that `POST` forms to your site. The default may change to `Lax` in the future. +The JavaScript SDK defaults to setting the SameSite option on its cookies to `None`. This can be overridden with the `sameSiteCookie` option. + `Lax` is recommended unless there are instances where you have third party sites that `POST` forms to your site. #### HttpOnly Cookies @@ -633,11 +658,17 @@ An HttpOnly option isn't technologically possible for Amplitude's SDK cookies. T #### Upgrading Legacy Cookies -Historically, Amplitude's cookies have been on the large side. Newly created cookies tend to be significantly smaller. For users that already have older cookies saved, the SDK will only remove old cookies and start using the newer more compact cookie format if the `cookieForceUpgrade` option is set to `true`. Note that if you use the SDK in multiple products, and track anonymous users across those products, you will want to be sure to set this option on all of those products. We would only recommend doing this if you are running into problems with over sized cookies. +Amplitude's legacy cookies were larger than the newer, more compact cookies. + For users that have older cookies, the SDK only removes old cookies and starts using the new cookie format if the `cookieForceUpgrade` option is set to `true`. + If you use the SDK in multiple products, and track anonymous users across those products, you be sure to set this option on all those products. + +!!!note + Upgrading cookies is only recommended if you are running into problems with oversized cookies. ### RequireJS -If you are using RequireJS to load your JavaScript files, then you can also use it to load the Amplitude JavaScript SDK script directly instead of using our loading snippet. If you take this approach you will lose one of the key advantages of the snippet that allows your app to start and use the Amplitude SDK without having to wait for Amplitude to fully download. +If you are using RequireJS to load your JavaScript files, then you can also use it to load the Amplitude JavaScript SDK script directly instead of using the loading snippet. + If you take this approach you lose one of the key advantages of the snippet that lets your app to start and use the Amplitude SDK without having to wait for Amplitude to fully download. ```js @@ -676,12 +707,13 @@ You can also define the path in your RequireJS configuration like this: ### Cross Domain Tracking (JavaScript) -You can track anonymous behavior across two different domains. Anonymous users are identified by their Device IDs which will need to be passed between the domains. For example: +You can track anonymous behavior across two different domains. Anonymous users are identified by their Device IDs which must be passed between the domains. For example: - Site 1: `www.example.com` - Site 2: `www.example.org` -Users who start on Site 1 and then navigate to Site 2 will need to have the Device ID generated from Site 1 passed as a parameter to Site 2. Site 2 then needs to initialize the SDK with that Device ID. The SDK can parse the URL parameter automatically if `deviceIdFromUrlParam` is enabled. +Users who start on Site 1 and then navigate to Site 2 need to have the Device ID generated from Site 1 passed as a parameter to Site 2. Site 2 then needs to initialize the SDK with that Device ID. + The SDK can parse the URL parameter automatically if `deviceIdFromUrlParam` is enabled. - From Site 1, grab the Device ID from `amplitude.getInstance().options.deviceId`. - Pass the Device ID to Site 2 via a URL parameter when the user navigates. (for example: `www.example.com?amp_device_id=device_id_from_site_1`) @@ -700,18 +732,20 @@ If tracking is enabled, then the SDK sets the values as user properties (for exa When these values are set, they never change. This is known as first touch attribution. !!!note "`saveParamsReferrerOncePerSession`" - By default, the SDK only saves the values at the start of the session. For example, if a user lands on your site with an initial set of UTM parameters and triggers some flow that causes them + By default, the SDK saves the values only at the start of the session. For example, if a user lands on your site with an initial set of UTM parameters and triggers some flow that causes them to land on your site again with a different set of UTM parameters within the same Amplitude session, the second set isn't saved. You can set the configuration option `saveParamsReferrerOncePerSession` to `false` to remove that restriction so that the SDK always captures new values from the user. !!!note "`unsetParamsReferrerOnNewSession`" - By default, the SDK carries over existing UTM Parameters and Referrer values at the start of a new session. For example, if a users session expires, the SDK maps the user's Referrer and UTM Parameters to existing values.  + By default, the SDK carries over existing UTM Parameters and Referrer values at the start of a new session. For example, + if a users session expires, the SDK maps the user's Referrer and UTM Parameters to existing values. To reset those values to null upon instantiating a new session, set `unsetParamsReferrerOnNewSession` to `true`. ### Callbacks for logEvent, Identify, and Redirect -You can pass a callback function to `logEvent` and identify, which gets called after receiving a response from the server. This is useful if timing may cause an event to not be captured before the browser navigates away from a webpage. - Putting the navigation in a callback to the logEvent method will guarantee the event is captured before the navigation occurs. Here is a logEvent example: +You can pass a callback function to `logEvent` and identify, which gets called after receiving a response from the server. +This is useful if timing may cause an event to not be captured before the browser navigates away from a webpage. + Putting the navigation in a callback to the `logEvent` method guarantees the event is captured before the navigation occurs. Here is a logEvent example: ```js amplitude.getInstance().logEvent("EVENT_TYPE", null, callback_function); @@ -757,7 +791,9 @@ In the case that `optOut` is `true`, then no event is logged but the callback is ### Error Callbacks -You can pass a second callback to `logEvent` and identify that will be called if the network request for the event fails. This is useful to detect if a user is using an ad blocker, or if there's an error from the Amplitude server due to an issue with the event format. You can use the error callback together with the success callback like this: +You can pass a second callback to `logEvent` and identify that are called if the network request for the event fails. + This is useful to detect if a user is using an ad blocker, or if there's an error from the Amplitude server due to an issue with the event format. + You can use the error callback together with the success callback like this: ```js var successCallback = function() { @@ -773,7 +809,7 @@ amplitude.getInstance().logEvent('event', null, successCallback, errorCallback); ### init Callbacks -You can also pass a callback function to init, which will get called after the SDK finishes its asynchronous loading. Note: The instance is passed as an argument to the callback: +You can also pass a callback function to init, which is called after the SDK finishes its asynchronous loading. The instance is passed as an argument to the callback: ```js amplitude.getInstance().init('API_KEY', 'USER_ID', null, function(instance) { @@ -783,7 +819,9 @@ amplitude.getInstance().init('API_KEY', 'USER_ID', null, function(instance) { ### Using sendBeacon -In SDK version 8.5.0 and above, the SDK can send events using the browser's built-in navigator.sendBeacon API. Unlike standard network requests, events sent by sendBeacon are sent in the background, and will be completed even if the user quickly closes the browser or leaves the page. However, because these events are sent in the background, it's not known if the event successfully uploads to the Amplitude server, and can't be saved for a later retry. +In SDK version 8.5.0 and above, the SDK can send events using the browser's built-in navigator.sendBeacon API. + Unlike standard network requests, events sent by sendBeacon are sent in the background, and are completed even if the user closes the browser or leaves the page. + However, because these events are sent in the background, it's not known if the event uploads to the Amplitude server, and can't be saved to retry later. To send an event using sendBeacon, set the transport SDK option to 'beacon' in one of two ways @@ -807,7 +845,8 @@ amplitude.getInstance().logEvent('send event with http'); #### Using sendBeacon only when exiting page -Configuring sendBeacon to send data only when the user exits a page can be complicated, so the JavaScript SDK provides a convenient callback function that's called only when the user exits the page, and automatically switches the transport to 'beacon' for any logs sent in the callback. This callback is called 'onExitPage' and is passed into the SDK on initialization, like so: +Configuring sendBeacon to send data only when the user exits a page can be complicated, so the JavaScript SDK provides a convenient callback function that's called only when the user exits the page, + and automatically switches the transport to 'beacon' for any logs sent in the callback. This callback is called `onExitPage` and is passed into the SDK on initialization, like so: ```js var exitCallback = function { @@ -817,7 +856,7 @@ var exitCallback = function { amplitude.getInstance().init('API_KEY', 'USER_ID', { onExitPage: exitCallback }); ``` -### Custom Device IDs +### Custom device IDs By default, device IDs are randomly generated UUIDs, although you can define a custom device ID by setting it as a configuration option or by calling: @@ -828,6 +867,9 @@ amplitude.getInstance().setDeviceId('DEVICE_ID'); You can retrieve the Device ID that Amplitude uses with `Amplitude.getInstance().getDeviceId().` This method can return `null` if a `deviceId` hasn't been generated yet. !!!note - This isn't recommended unless you have your own system for tracking user devices. Make sure the `deviceId` you set is unique to prevent conflicts with other devices in your Amplitude data. We recommend something like a UUID. + This isn't recommended unless you have your own system for tracking user devices. Make sure the `deviceId` you set is unique to prevent conflicts with other devices in your Amplitude data. + It's best practice to use something like a UUID. See [here](https://github.com/amplitude/Amplitude-Javascript/blob/master/src/uuid.js) for an example of how to generate on JavaScript. + +--8<-- "includes/abbreviations.md" diff --git a/includes/abbreviations.md b/includes/abbreviations.md index bcee031a5..51aada3ec 100644 --- a/includes/abbreviations.md +++ b/includes/abbreviations.md @@ -1,4 +1,6 @@ *[CCPA]: California Consumer Privacy Act *[GDPR]: General Data Protection Regulation *[SLA]: Service level agreement -*[COPPA]: Children's Online Privacy Protection Act \ No newline at end of file +*[COPPA]: Children's Online Privacy Protection Act +*[UUID]: Universally unique identifier +*[UUIDs]: Universally unique identifiers \ No newline at end of file diff --git a/vale/styles/write-good/ThereIs.yml b/vale/styles/write-good/ThereIs.yml deleted file mode 100644 index 8b82e8f6c..000000000 --- a/vale/styles/write-good/ThereIs.yml +++ /dev/null @@ -1,6 +0,0 @@ -extends: existence -message: "Don't start a sentence with '%s'." -ignorecase: false -level: error -raw: - - '(?:[;-]\s)There\s(is|are)|\bThere\s(is|are)\b' diff --git a/vale/styles/write-good/TooWordy.yml b/vale/styles/write-good/TooWordy.yml index 275701b19..99c8b97d3 100644 --- a/vale/styles/write-good/TooWordy.yml +++ b/vale/styles/write-good/TooWordy.yml @@ -143,7 +143,6 @@ tokens: - minimum - modify - monitor - - multiple - necessitate - nevertheless - not certain From b3034fda0efdbddcc7ce8f26934d027f3f86dd71 Mon Sep 17 00:00:00 2001 From: caseyamp Date: Mon, 14 Mar 2022 13:38:59 -0700 Subject: [PATCH 04/13] Dynamic Config --- docs/analytics/dynamic-configuration.md | 66 +++++++++++++++++++++++++ mkdocs.yml | 2 + 2 files changed, 68 insertions(+) create mode 100644 docs/analytics/dynamic-configuration.md diff --git a/docs/analytics/dynamic-configuration.md b/docs/analytics/dynamic-configuration.md new file mode 100644 index 000000000..8c83cd553 --- /dev/null +++ b/docs/analytics/dynamic-configuration.md @@ -0,0 +1,66 @@ +--- +title: Dynamic Configuration +description: Use dynamic configuration to find the best server URLs based on a user's location. +--- + +Some Amplitude SDK versions (iOS 5.3.0+, Android 2.28.0+, and JavaScript 8.9.0+) let you set your apps to use dynamic configuration. + Dynamic configuration finds the best Amplitude server URL based on app users' location. + +## Considerations + +- If you have your own proxy server and use `setServerUrl` API, don't use dynamic configuration. +- If you have users in Mainland China, we recommend that you use dynamic configuration. +- By default, this feature is off. You must explicitly set it to `true` to use it. + +## Use cases + +### Region-based + +Send users from different regions to the server for their region. + +``` mermaid +stateDiagram-v2 + s1: Dynamic Config Server + cn_user: User in China + us_user: User in United States + s1 --> cn_user : api2.amplitude.com + s1 --> us_user : api.amplitude.com + +``` + +### Dynamically adjust server URLs + +If a server URL becomes unreachable for some reason, Amplitude can change the address in the dynamic configuration server. + This makes the ingestion endpoint dynamic, so you don't need to release a new version of your app. + +``` mermaid +stateDiagram-v2 + s1: Dynamic Config Server + user: User + s1 --> user : new.amplitude.com (new URL) + s1 --> user : old.amplitude.com (broken URL) +``` + +## Usage + +Set the `useDynamicConfig` flag to `true`. + +=== "iOS" + + ```obj-c + [Amplitude instance].useDynamicConfig = YES; + ``` + +=== "Android" + + ```java + AmplitudeClient.getInstance().setUseDynamicConfig(true); + ``` + +=== "JavaScript" + + ```js + amplitude.getInstance().init(euApiKey, null, { + useDynamicConfig: true, + }); + ``` diff --git a/mkdocs.yml b/mkdocs.yml index 0b0d75aea..d6874662b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -132,6 +132,8 @@ nav: - Amplitude SDKs: - analytics/sdks/android-sdk.md - analytics/sdks/javascript-sdk.md + - Other Resources: + - analytics/dynamic-configuration.md - Experiment: - experiment/index.md - Data: From 731c75f76b44ba8f73f42cabdfdd1c4e1e0f60fc Mon Sep 17 00:00:00 2001 From: caseyamp Date: Tue, 15 Mar 2022 09:16:57 -0700 Subject: [PATCH 05/13] Making updates to android and JS sdk --- docs/analytics/sdks/android-sdk.md | 2 +- docs/analytics/sdks/javascript-sdk.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/analytics/sdks/android-sdk.md b/docs/analytics/sdks/android-sdk.md index d24bf1093..ede973fef 100644 --- a/docs/analytics/sdks/android-sdk.md +++ b/docs/analytics/sdks/android-sdk.md @@ -962,7 +962,7 @@ Second, add the following code in your root activity's onCreate life cycle. ### Dynamic Configuration -Android SDK allows users to configure their apps to use [dynamic configuration](https://developers.amplitude.com/docs/dynamic-configuration). This feature finds the best server URL automatically based on app users' location. +Android SDK allows users to configure their apps to use [dynamic configuration](analytics/dynamic-configuration). This feature finds the best server URL automatically based on app users' location. - If you have your own proxy server and use `setServerUrl` API, leave dynamic configuration off. - If you have users in China Mainland, then we recommend using dynamic configuration. diff --git a/docs/analytics/sdks/javascript-sdk.md b/docs/analytics/sdks/javascript-sdk.md index 4b991b153..62ce3c0f4 100644 --- a/docs/analytics/sdks/javascript-sdk.md +++ b/docs/analytics/sdks/javascript-sdk.md @@ -588,7 +588,7 @@ Amplitude's JavaScript SDK supports integration with Google Tag Manager. See the ### Dynamic Configuration -Beginning with version 8.9.0, the JavaScript SDK allows users to configure their apps to use [dynamic configuration](https://developers.amplitude.com/docs/dynamic-configuration). +Beginning with version 8.9.0, the JavaScript SDK allows users to configure their apps to use [dynamic configuration](analytics/dynamic-configuration). This feature finds the best server URL automatically based on app users' location. To use, set `useDynamicConfig` to `true`. @@ -645,7 +645,7 @@ The cookie is used to keep track of metadata for the SDK: Amplitude cookies can be disabled altogether using the `disableCookies` option. When you disable cookies, the JavaScript SDK defaults to using `localStorage` to store its data. LocalStorage is a great alternative, but can't track cookies across domains. - Beause access to `localStorage` is restricted by subdomain, you can't track anonymous users across subdomains of your product (for example: `www.amplitude.com` vs `analytics.amplitude.com`). + Because access to `localStorage` is restricted by subdomain, you can't track anonymous users across subdomains of your product (for example: `www.amplitude.com` vs `analytics.amplitude.com`). #### SameSite From a8c7ecd60b6bc0545256dae9a4f13de30b293e8f Mon Sep 17 00:00:00 2001 From: caseyamp Date: Tue, 15 Mar 2022 12:34:51 -0700 Subject: [PATCH 06/13] update broken link --- docs/analytics/sdks/javascript-sdk.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/analytics/sdks/javascript-sdk.md b/docs/analytics/sdks/javascript-sdk.md index 62ce3c0f4..8d1348ec2 100644 --- a/docs/analytics/sdks/javascript-sdk.md +++ b/docs/analytics/sdks/javascript-sdk.md @@ -588,7 +588,7 @@ Amplitude's JavaScript SDK supports integration with Google Tag Manager. See the ### Dynamic Configuration -Beginning with version 8.9.0, the JavaScript SDK allows users to configure their apps to use [dynamic configuration](analytics/dynamic-configuration). +Beginning with version 8.9.0, the JavaScript SDK allows users to configure their apps to use [dynamic configuration](../dynamic-configuration.md). This feature finds the best server URL automatically based on app users' location. To use, set `useDynamicConfig` to `true`. From b65756125b668083eedb7bb57586e8547ec5e163 Mon Sep 17 00:00:00 2001 From: Casey <96889984+caseyamp@users.noreply.github.com> Date: Mon, 21 Mar 2022 14:32:20 -0700 Subject: [PATCH 07/13] Update docs/analytics/sdks/javascript-sdk.md Co-authored-by: Kevin Pagtakhan --- docs/analytics/sdks/javascript-sdk.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/analytics/sdks/javascript-sdk.md b/docs/analytics/sdks/javascript-sdk.md index 8d1348ec2..6817fd535 100644 --- a/docs/analytics/sdks/javascript-sdk.md +++ b/docs/analytics/sdks/javascript-sdk.md @@ -145,7 +145,7 @@ amplitude.getInstance().init(euApiKey, null, { Events represent how users interact with your application. For example, “Button Clicked” may be an action you want to note. ```js -var event = “Button Clicked”; +const event = “Button Clicked”; amplitude.getInstance().logEvent(event); ``` From 44a463fc2659e2a2c27fffaf81396ca1d74d126e Mon Sep 17 00:00:00 2001 From: Casey <96889984+caseyamp@users.noreply.github.com> Date: Mon, 21 Mar 2022 14:32:32 -0700 Subject: [PATCH 08/13] Update docs/analytics/sdks/javascript-sdk.md Co-authored-by: Kevin Pagtakhan --- docs/analytics/sdks/javascript-sdk.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/analytics/sdks/javascript-sdk.md b/docs/analytics/sdks/javascript-sdk.md index 6817fd535..cd35080bf 100644 --- a/docs/analytics/sdks/javascript-sdk.md +++ b/docs/analytics/sdks/javascript-sdk.md @@ -154,7 +154,7 @@ amplitude.getInstance().logEvent(event); Events can also contain properties. They give context about the event taken. For example, “hover time” may be a relevant event property to “Button Clicked”. ```js -var event = “Button Clicked”; +var event = "Button Clicked"; var eventProperties = { "hover time": "100ms" }; From 8d766eaa27fd748dd168d0e132f83f6ac53c588d Mon Sep 17 00:00:00 2001 From: Casey <96889984+caseyamp@users.noreply.github.com> Date: Mon, 21 Mar 2022 14:33:52 -0700 Subject: [PATCH 09/13] Update docs/analytics/sdks/javascript-sdk.md Co-authored-by: Kevin Pagtakhan --- docs/analytics/sdks/javascript-sdk.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/analytics/sdks/javascript-sdk.md b/docs/analytics/sdks/javascript-sdk.md index cd35080bf..21d41602b 100644 --- a/docs/analytics/sdks/javascript-sdk.md +++ b/docs/analytics/sdks/javascript-sdk.md @@ -398,7 +398,7 @@ Events triggered within 30 minutes of each other are counted towards the current In the JavaScript SDK, you can use the helper method _sessionId to get the value of the current sessionId: ```js -var sessionId = amplitude.getInstance()._sessionId; +const sessionId = amplitude.getInstance().getSessionId(); ``` ### Configuring HTTP Headers From 1d76a6b2e0449feb8532cba08b5d719791d41767 Mon Sep 17 00:00:00 2001 From: Casey <96889984+caseyamp@users.noreply.github.com> Date: Mon, 21 Mar 2022 14:34:11 -0700 Subject: [PATCH 10/13] Update docs/analytics/sdks/javascript-sdk.md Co-authored-by: Kevin Pagtakhan --- docs/analytics/sdks/javascript-sdk.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/analytics/sdks/javascript-sdk.md b/docs/analytics/sdks/javascript-sdk.md index 21d41602b..cfa995fa3 100644 --- a/docs/analytics/sdks/javascript-sdk.md +++ b/docs/analytics/sdks/javascript-sdk.md @@ -610,7 +610,7 @@ amplitude.getInstance().init(euApiKey, null, { You can get a user's current Device ID with the following code: ```js -var deviceId = amplitude.getInstance().options.deviceId; // existing device ID +var deviceId = amplitude.getInstance().getDeviceId() // existing device ID ``` ### Setting Configuration Options From 35a4fac46132fa52bb19f9ad304b700970762872 Mon Sep 17 00:00:00 2001 From: caseyamp Date: Mon, 21 Mar 2022 14:48:43 -0700 Subject: [PATCH 11/13] more style changes --- docs/analytics/sdks/javascript-sdk.md | 54 ++++++++++++++------------- 1 file changed, 28 insertions(+), 26 deletions(-) diff --git a/docs/analytics/sdks/javascript-sdk.md b/docs/analytics/sdks/javascript-sdk.md index 8d1348ec2..59d45a45f 100644 --- a/docs/analytics/sdks/javascript-sdk.md +++ b/docs/analytics/sdks/javascript-sdk.md @@ -29,7 +29,7 @@ You can install the JavaScript SDK using a small snippet of code which you paste ;n.type="text/javascript" ;n.integrity="sha384-4rr7CTymHc64YjTTL6O3ktfsHYI1yJnQdmKv4zFoe+frjXb05MfzzuLLIAgJ/XHs" ;n.crossOrigin="anonymous";n.async=true -;n.src="https://cdn.amplitude.com/libs/amplitude-8.11.0-min.gz.js" +;n.src="https://cdn.amplitude.com/libs/amplitude-8.17.0-min.gz.js" ;n.onload=function(){if(!e.amplitude.runQueuedFunctions){ console.log("[Amplitude] Error: could not load SDK")}} ;var s=t.getElementsByTagName("script")[0];s.parentNode.insertBefore(n,s) @@ -248,8 +248,8 @@ amplitude.getInstance().identify(identify); #### `prepend` and `append` -- `append` will append a value or values to a user property array. -- `prepend` will prepend a value or values to a user property. +- `append` appends a value or values to a user property array. +- `prepend` prepends a value or values to a user property. If the user property doesn't have a value set yet, it's initialized to an empty list before the new values are added. If the user property has an existing value and it's not a list, it's converted into a list with the new value added. @@ -361,7 +361,7 @@ By default, the JavaScript SDK tracks some properties automatically. You can ove If you have a project with existing data that you would like to stop collecting the default properties for, please contact the Support team at support.amplitude.com. Note that the existing data isn't deleted. -### Setting Custom User ID +### Setting custom user ID If your app has its own login system that you want to track users with, you can call `setUserId` at any time: @@ -387,13 +387,13 @@ amplitude.getInstance().setUserId(null); // not string 'null' amplitude.getInstance().regenerateDeviceId(); ``` -### Session Tracking +### Session tracking Events triggered within 30 minutes of each other are counted towards the current session. The time of the first event marks the start time of a session and the last event triggered marks the end time of a session. You can change the session timeout window via the SDK configuration option field `sessionTimeout`. -#### Getting the Session ID +#### Getting the session ID In the JavaScript SDK, you can use the helper method _sessionId to get the value of the current sessionId: @@ -401,7 +401,7 @@ In the JavaScript SDK, you can use the helper method _sessionId to get the value var sessionId = amplitude.getInstance()._sessionId; ``` -### Configuring HTTP Headers +### Configuring HTTP headers If you are using a [domain proxy](https://developers.amplitude.com/docs/domain-proxies) that requires custom HTTP request headers, configure them with `options.headers` during initialization. @@ -414,7 +414,7 @@ amplitude.getInstance().init(APIKEY, null, { }); ``` -### Logging Events to Multiple Projects +### Logging events to multiple projects If you want to log events to multiple Amplitude projects, then must have separate instances for each Amplitude project. Each instance allows for independent `apiKeys`, `userIds`, `deviceIds`, and settings. @@ -448,7 +448,7 @@ amplitude.getInstance().identify(identify); amplitude.getInstance().logEvent('Viewed Home Page'); ``` -### Web Attribution +### Web attribution While Amplitude’s JavaScript SDK doesn't collect web attribution data by default, setting it up is simple. The SDK can automatically collect this information if you enable attribution configuration options. @@ -460,7 +460,7 @@ Amplitude supports automatically tracking the following through the SDK configur - Google Click Identifier from URL parameters through `includeGclid`. - Facebook Click Identifier from URL parameters through `includeFbclid`. -#### Track UTM Parameters +#### Track UTM parameters UTM parameters stand for Urchin Traffic Monitor parameters and are useful for analyzing the effectiveness of different ad campaigns and referring sites. UTM parameters are case sensitive so they're considered different values if the capitalization varies. @@ -489,7 +489,7 @@ UTM parameters are captured once per session by default and occurs when the user it pulls the UTM parameters that are available at the time. Those UTM parameters are set as user properties which persists for all the user's events going forward. However, initial UTM parameters are captured only once for each user via a `setOnce` operation. -#### Track Referrers +#### Track referrers If you want to track how users are getting to your website, then track the referrer (the referring site). @@ -507,7 +507,7 @@ After you set the `includeReferrer` option to `true`, Amplitude captures the `re Initial referring information is captured only once for each user via a `setOnce` operation. -#### First-Touch Attribution +#### First-touch attribution Amplitude can capture the initial UTM parameters and referrer information for each user. The first-touch attribution values are set when a user's non-null UTM parameters are seen for the first time. These user properties are set once: @@ -527,7 +527,7 @@ This is done by setting the JavaScript SDK configuration options `includeReferre !!!note Initial attribution information for users can change if they're merged with another user. -#### Last-Touch Attribution +#### Last-touch attribution In addition to first-touch attribution, Amplitude captures where a user came from for each of their sessions by setting these user properties: @@ -544,7 +544,7 @@ In addition to first-touch attribution, Amplitude captures where a user came fro This is done by setting the JavaScript SDK configuration options `includeReferrer`, `includeUtm`, and `includeGclid` to `true`. By default, the SDK only saves values at the start of the session so if a user triggers some flow that causes them to land on the site again with a different set of UTM parameters within the same session, that second set isn't saved. -#### Multi-Touch Attribution +#### Multi-touch attribution If you set `saveParamsReferrerOncePerSession` to `false` in your JavaScript SDK configuration, the SDK always capture any new values from the user. This updates these user properties throughout a session if they change: @@ -560,7 +560,9 @@ If you set `saveParamsReferrerOncePerSession` to `false` in your JavaScript SDK Some customers also instrument these user properties as arrays to keep track of all the attribution parameters seen within the same session for a single user. -#### Logging Captured Attribution Values via Amplitude (Advanced Use Case) +#### Logging captured attribution values via Amplitude + +This is an advanced use case. !!!important @@ -586,7 +588,7 @@ If you set `logAttributionCapturedEvent` to `true` in your JavaScript SDK config Amplitude's JavaScript SDK supports integration with Google Tag Manager. See the [demo app](https://github.com/amplitude/GTM-Web-Demo) on GitHub for instructions on how to set it up. -### Dynamic Configuration +### Dynamic configuration Beginning with version 8.9.0, the JavaScript SDK allows users to configure their apps to use [dynamic configuration](../dynamic-configuration.md). This feature finds the best server URL automatically based on app users' location. @@ -613,7 +615,7 @@ You can get a user's current Device ID with the following code: var deviceId = amplitude.getInstance().options.deviceId; // existing device ID ``` -### Setting Configuration Options +### Setting configuration options You can configure Amplitude by passing an object as the third argument to the init: @@ -626,9 +628,9 @@ amplitude.getInstance().init("API_KEY", null, { }) ``` -### Cookie Management +### Cookie management -#### Cookies Created by the SDK +#### Cookies created by the SDK On initialization, the SDK creates a cookie that begins with the prefix `amp_` and ends with this first six digits of your API key. For example, `amplitude.getInstance().init("a2dbce0e18dfe5f8e74493843ff5c053")` would create a cookie with the key `amp_a2dbce`. @@ -641,7 +643,7 @@ The cookie is used to keep track of metadata for the SDK: - The last event time - Sequence IDs to put events and identify operations in the correct order -#### Disabling Cookies +#### Disabling cookies Amplitude cookies can be disabled altogether using the `disableCookies` option. When you disable cookies, the JavaScript SDK defaults to using `localStorage` to store its data. LocalStorage is a great alternative, but can't track cookies across domains. @@ -652,11 +654,11 @@ Amplitude cookies can be disabled altogether using the `disableCookies` option The JavaScript SDK defaults to setting the SameSite option on its cookies to `None`. This can be overridden with the `sameSiteCookie` option. `Lax` is recommended unless there are instances where you have third party sites that `POST` forms to your site. -#### HttpOnly Cookies +#### HttpOnly cookies An HttpOnly option isn't technologically possible for Amplitude's SDK cookies. The cookie is set on the client side and is used as a client-side data store. An SDK cookie can't set the HttpOnly flag. -#### Upgrading Legacy Cookies +#### Upgrading legacy cookies Amplitude's legacy cookies were larger than the newer, more compact cookies. For users that have older cookies, the SDK only removes old cookies and starts using the new cookie format if the `cookieForceUpgrade` option is set to `true`. @@ -705,7 +707,7 @@ You can also define the path in your RequireJS configuration like this: ``` -### Cross Domain Tracking (JavaScript) +### Cross domain tracking (JavaScript) You can track anonymous behavior across two different domains. Anonymous users are identified by their Device IDs which must be passed between the domains. For example: @@ -719,7 +721,7 @@ Users who start on Site 1 and then navigate to Site 2 need to have the Device ID - Pass the Device ID to Site 2 via a URL parameter when the user navigates. (for example: `www.example.com?amp_device_id=device_id_from_site_1`) - Initialize the Amplitude SDK on Site 2 with `amplitude.init('API_KEY', null, {deviceIdFromUrlParam: true})`. -### Tracking UTM Parameters, Referrer, and gclid (JavaScript) +### Tracking UTM parameters, referrer, and gclid (JavaScript) Amplitude supports automatically tracking: @@ -789,7 +791,7 @@ In the case that `optOut` is `true`, then no event is logged but the callback is In the case that `batchEvents` is `true`, if the batch requirements `eventUploadThreshold` and `eventUploadPeriodMillis` aren't met when `logEvent` is called, then no request is sent but the callback is still called. In these cases, the callback is called with an input status of 0 and a response of 'No request sent'. -### Error Callbacks +### Error callbacks You can pass a second callback to `logEvent` and identify that are called if the network request for the event fails. This is useful to detect if a user is using an ad blocker, or if there's an error from the Amplitude server due to an issue with the event format. @@ -807,7 +809,7 @@ var errorCallback = function() { amplitude.getInstance().logEvent('event', null, successCallback, errorCallback); ``` -### init Callbacks +### `init` callbacks You can also pass a callback function to init, which is called after the SDK finishes its asynchronous loading. The instance is passed as an argument to the callback: From f8674fdfa5437565743c1b658b951783a4e82681 Mon Sep 17 00:00:00 2001 From: caseyamp Date: Tue, 22 Mar 2022 08:10:56 -0700 Subject: [PATCH 12/13] Making some tweaks to reusables and sdks based on feedback --- docs/analytics/dynamic-configuration.md | 2 +- docs/analytics/sdks/android-sdk.md | 10 ++++- docs/analytics/sdks/javascript-sdk.md | 51 ++++++++++++---------- includes/sdkresources.md | 4 +- includes/track-revenue-properties-table.md | 4 +- 5 files changed, 45 insertions(+), 26 deletions(-) diff --git a/docs/analytics/dynamic-configuration.md b/docs/analytics/dynamic-configuration.md index 8c83cd553..a69c22036 100644 --- a/docs/analytics/dynamic-configuration.md +++ b/docs/analytics/dynamic-configuration.md @@ -43,7 +43,7 @@ stateDiagram-v2 ## Usage -Set the `useDynamicConfig` flag to `true`. +Enable the `useDynamicConfig` flag. === "iOS" diff --git a/docs/analytics/sdks/android-sdk.md b/docs/analytics/sdks/android-sdk.md index ede973fef..5e51ab6a9 100644 --- a/docs/analytics/sdks/android-sdk.md +++ b/docs/analytics/sdks/android-sdk.md @@ -508,7 +508,15 @@ Amplitude can track revenue generated by a user. Revenue is tracked through dist Revenue objects support the following special properties, as well as user-defined properties through the `eventProperties` field. ---8<-- "includes/track-revenue-properties-table.md" +|
Name
| Description | +| --- | --- | +| `productId` | Optional. String. An identifier for the product. Amplitude recommends something like the "Google Play Store product ID". Defaults to `null`. | +| `quantity`| Required. Integer. The quantity of products purchased. Note: revenue = quantity * price. Defaults to 1. | +| `price` | Required. Double. The price of the products purchased, and this can be negative. Note: revenue = quantity * price. Defaults to `null`.| +| `revenueType` | Optional, but required for revenue verification. String. The type of revenue (e.g. tax, refund, income). Defaults to `null`. | +| `receipt` | Optional. String. The type of revenue (e.g. tax, refund, income). Defaults to `null` | +| `receiptSignature` | Optional, but required for revenue verification. The type of revenue (e.g. tax, refund, income). | null | +| `eventProperties`| Optional. JSONObject. An object of event properties to include in the revenue event. Defaults to `null`. | !!!note "Notes about tracking revenue" diff --git a/docs/analytics/sdks/javascript-sdk.md b/docs/analytics/sdks/javascript-sdk.md index 8b6d38589..daccc6fde 100644 --- a/docs/analytics/sdks/javascript-sdk.md +++ b/docs/analytics/sdks/javascript-sdk.md @@ -117,7 +117,7 @@ Set `userID` when initializing the client, or after initialization with the `set ### EU data residency Beginning with version 8.9.0, you can configure the server zone after initializing the client for sending data to Amplitude's EU servers. The SDK sends data based on the server zone if it's set. - The server zone config supports dynamic configuration as well. + The server zone configuration supports dynamic configuration as well. For earlier versions, you need to configure the `apiEndpoint` property after initializing the client. @@ -161,9 +161,11 @@ var eventProperties = { amplitude.getInstance().logEvent(event, eventProperties); ``` +Valid data types for event properties are string, array, object, boolean, and number. Object keys have a 1000 character limit. + #### Arrays in Event Properties -Arrays can be used as event property values. Array event properties can be queried by any subset of the individual properties in the array. +Arrays can be used as event property values. You can query array event properties by any subset of the individual properties in the array. ```js var event = “Button Clicked”; @@ -194,9 +196,9 @@ var identify = new amplitude.Identify(); amplitude.getInstance().identify(identify); // makes identify call to amplitude with the properties of the identify object ``` -#### set +#### `set` -`set` sets the value of a user property. You can also chain together multiple set calls. +`set` sets the value of a user property. You can also chain together many set calls. ```js var identify1 = new amplitude.Identify().set('key1', 'value1'); @@ -205,23 +207,22 @@ amplitude.getInstance().identify(identify1); amplitude.getInstance().identify(identify2); ``` -#### setOnce +#### `setOnce` -`setOnce` sets the value of a user property only once. Later calls using `setOnce` are ignored. +`setOnce` sets the value of a user property one time. Later calls using `setOnce` are ignored. ```js var identify = new amplitude.Identify().setOnce('key1', 'value1'); amplitude.getInstance().identify(identify); ``` -#### add +#### `add` -`add` increments a user property by some numerical value. If the user property doesn't have a value set yet, it's initialized to `0` before being incremented. +`add` increments a user property by some numerical value. If the user property doesn't have a value set yet, it's initialized to `0`. ```js var identify = new amplitude.Identify().add('value1', 10); amplitude.getInstance().identify(identify); - ``` #### Setting multiple user properties @@ -268,7 +269,7 @@ If the user property doesn't have a value set yet, it's initialized to an empty amplitude.getInstance().setGroup('orgId', '[10,16]'); ``` -You can also use `logEventWithGroups` to set event-level groups, meaning the group designation only applies for the specific event being logged and doesn't persist on the user unless you explicitly +You can also use `logEventWithGroups` to set event-level groups, meaning the group designation applies only for the specific event being logged, and doesn't persist on the user unless you explicitly set it with `setGroup`. ```js @@ -302,7 +303,7 @@ The preferred method of tracking revenue for a user is to use `logRevenueV2()` i You can also add event properties to revenue events via the eventProperties field. These Revenue instance objects are then passed into `logRevenueV2` to send as revenue events to Amplitude. This allows Amplitude to automatically display data relevant to revenue in the platform. You can use this to track both in-app and non-in-app purchases. -To track revenue from a user, call logRevenueV2() each time a user generates revenue. Here is an example: +To track revenue from a user, call `logRevenueV2()` each time a user generates revenue. Here is an example: ```js var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3); @@ -317,9 +318,15 @@ You can't change the default names given to these client-side revenue events in To learn more about tracking revenue, see the documentation [here](https://help.amplitude.com/hc/en-us/articles/115003116888). !!!note - Amplitude doesn't support currency conversion. All revenue data should be normalized to your currency of choice, before being sent to Amplitude. + Amplitude doesn't support currency conversion. Normalize all revenue data to your currency of choice before sending it to Amplitude. ---8<-- "includes/track-revenue-properties-table.md" +|
Name
| Description | +| --- | --- | +| `productId` | Optional. String. An identifier for the product. Amplitude recommends something like the "Google Play Store product ID". Defaults to `null`. | +| `quantity`| Required. Integer. The quantity of products purchased. Note: revenue = quantity * price. Defaults to 1. | +| `price` | Required. Double. The price of the products purchased, and this can be negative. Note: revenue = quantity * price. Defaults to `null`.| +| `revenueType` | Optional, but required for revenue verification. String. The revenue type. For example, tax, refund, income. Defaults to `null`. | +| `eventProperties`| Optional. Object. An object of event properties to include in the revenue event. Defaults to `null`. | ### Opt users out of tracking @@ -357,7 +364,7 @@ By default, the JavaScript SDK tracks some properties automatically. You can ove |`version_name` | `true`| !!!warning - The `trackingOptions` configurations only prevent default properties from being tracked on new projects that have no existing data. + The `trackingOptions` configurations prevent default properties from being tracked on new projects that have no existing data, not existing data. If you have a project with existing data that you would like to stop collecting the default properties for, please contact the Support team at support.amplitude.com. Note that the existing data isn't deleted. @@ -395,7 +402,7 @@ Events triggered within 30 minutes of each other are counted towards the current #### Getting the session ID -In the JavaScript SDK, you can use the helper method _sessionId to get the value of the current sessionId: +In the JavaScript SDK, you can use the helper method `getSessionId` to get the value of the current `sessionId`: ```js const sessionId = amplitude.getInstance().getSessionId(); @@ -481,13 +488,13 @@ Here is an example URL: In Amplitude, after you set the `includeUtm` option to true, the JavaScript SDK automatically pulls UTM parameters from the referring URL and include them as user properties on all relevant events: -- `includeGclid`: Gclid (Google Click Identifier) is a globally unique tracking parameter used by Google. If utilized, Google appends a unique parameter (for example: `"?gclid=734fsdf3"`) to URLs at runtime. By setting this to true, the SDK captures `initial_glid` and `gclid` as user properties. -- `includeFbclid`: Fbclid (Facebook Click Identifier) is a globally unique tracking parameter used by Facebook. If utilized, Facebook appends a unique parameter (for example: `"?fbclid=392foih3"`) to URLs at runtime. By setting this to true, the SDK captures `initial_fblid` and `fbclid` as user properties. -- `includeUtm`: If true, finds the standard UTM parameters from either the URL or the browser cookie and sets them as user properties. This sets `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, and `utm_content` as well as `initial_utm_source`, `initial_utm_medium`, `initial_utm_campaign`, `initial_utm_term`, and `initial_utm_content` as user properties for the user. +- `includeGclid`: Gclid (Google Click Identifier) is a globally unique tracking parameter used by Google. If used, Google appends a unique parameter (for example: `"?gclid=734fsdf3"`) to URLs at runtime. By setting this to true, the SDK captures `initial_glid` and `gclid` as user properties. +- `includeFbclid`: Fbclid (Facebook Click Identifier) is a globally unique tracking parameter used by Facebook. If used, Facebook appends a unique parameter (for example: `"?fbclid=392foih3"`) to URLs at runtime. By setting this to `true`, the SDK captures `initial_fblid` and `fbclid` as user properties. +- `includeUtm`: If `true`, finds the standard UTM parameters from either the URL or the browser cookie and sets them as user properties. This sets `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, and `utm_content` as well as `initial_utm_source`, `initial_utm_medium`, `initial_utm_campaign`, `initial_utm_term`, and `initial_utm_content` as user properties for the user. UTM parameters are captured once per session by default and occurs when the user loads your site and the Amplitude SDK for the first time. You can disable the once per session restriction through the `saveParamsReferrerOncePerSession` configuration option. When the SDK detects that it should start a new session, it pulls the UTM parameters that are available at the time. Those UTM parameters are set as user properties which persists for all the user's events going forward. - However, initial UTM parameters are captured only once for each user via a `setOnce` operation. + However, initial UTM parameters are captured once for each user via a `setOnce` operation. #### Track referrers @@ -503,9 +510,9 @@ Amplitude supports tracking these fields automatically: After you set the `includeReferrer` option to `true`, Amplitude captures the `referrer` and `referring_domain` for each session and set them as user properties on relevant events: - `includeReferrer`: When `true`, captures the `referrer` and `referring_domain` for each session as user properties as well as the `initial_referrer` and `initial_referring_domain` user properties once for each user. - The referrer is the entire URL while the `referring_domain` is only the domain name from where the user came from. + The referrer is the entire URL while the `referring_domain` is the domain name from where the user came from. -Initial referring information is captured only once for each user via a `setOnce` operation. +Initial referring information is captured one time for each user via a `setOnce` operation. #### First-touch attribution @@ -542,7 +549,7 @@ In addition to first-touch attribution, Amplitude captures where a user came fro - `fbclid` This is done by setting the JavaScript SDK configuration options `includeReferrer`, `includeUtm`, and `includeGclid` to `true`. - By default, the SDK only saves values at the start of the session so if a user triggers some flow that causes them to land on the site again with a different set of UTM parameters within the same session, that second set isn't saved. + By default, the SDK only saves values at the start of the session, so if a user triggers some flow that causes them to land on the site again with a different set of UTM parameters within the same session, the second set isn't saved. #### Multi-touch attribution diff --git a/includes/sdkresources.md b/includes/sdkresources.md index 746bff3e6..7a86b71e1 100644 --- a/includes/sdkresources.md +++ b/includes/sdkresources.md @@ -1,4 +1,6 @@ ???info "SDK Resources" - [JavaScript SDK Reference :material-book:](https://amplitude.github.io/Amplitude-JavaScript/) - [JavaScript SDK Repo :material-github:](https://github.com/amplitude/Amplitude-JavaScript) - - [JavaScript SDK Releases :material-code-tags-check:](https://github.com/amplitude/Amplitude-Javascript/releases) \ No newline at end of file + - [JavaScript SDK Releases :material-code-tags-check:](https://github.com/amplitude/Amplitude-Javascript/releases) + + \ No newline at end of file diff --git a/includes/track-revenue-properties-table.md b/includes/track-revenue-properties-table.md index 16310ddec..6f8f153ea 100644 --- a/includes/track-revenue-properties-table.md +++ b/includes/track-revenue-properties-table.md @@ -6,4 +6,6 @@ | `revenueType` | Optional, but required for revenue verification. String. The type of revenue (e.g. tax, refund, income). Defaults to `null`. | | `receipt` | Optional. String. The type of revenue (e.g. tax, refund, income). Defaults to `null` | | `receiptSignature` | Optional, but required for revenue verification. The type of revenue (e.g. tax, refund, income). | null | -| `eventProperties`| Optional. JSONObject. An object of event properties to include in the revenue event. Defaults to `null`. | \ No newline at end of file +| `eventProperties`| Optional. JSONObject. An object of event properties to include in the revenue event. Defaults to `null`. | + + \ No newline at end of file From afe21ce7a862cacd9c3ed39671d798b78a3aa2ec Mon Sep 17 00:00:00 2001 From: caseyamp Date: Thu, 24 Mar 2022 10:08:38 -0700 Subject: [PATCH 13/13] Making final tweaks --- docs/analytics/sdks/javascript-sdk.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/analytics/sdks/javascript-sdk.md b/docs/analytics/sdks/javascript-sdk.md index daccc6fde..14efb179b 100644 --- a/docs/analytics/sdks/javascript-sdk.md +++ b/docs/analytics/sdks/javascript-sdk.md @@ -27,7 +27,7 @@ You can install the JavaScript SDK using a small snippet of code which you paste