Customer Data Platform Web SDK

Customer Data Platform Web SDK is a low-level API that you can use to configure your website to send events to Customer Data Platform. The process involves configuring your website to collect and submit both customer engagement and user profile data to Customer Data Platform. The built-in consent management system ensures that you only collect data from users that choose to allow it. You can make most of these calls from within the application interface, or you can call these methods externally using your tenant-specific endpoint.

A newer version of the Web SDK is available. If you have not already implemented the Customer Data Platform Web SDK version, we recommend implementing the latest Salesforce Interactions SDK version.

Important

Prerequisites

To use Customer Data Platform Web SDK, create a Salesforce data source connector. Log into Customer Data Platform and set up a web connector. For additional setup information, see the Customer Data Platform Implementation Guide.

Use the Source ID and tenant-specific endpoint from your website connector to initialize the Customer Data Platform Web SDK.

Download the SDK

Download the source for the Customer Data Platform Web SDK from:

Configuring the SDK

The Web SDK consumes this configuration object to automatically generate and assigns event listeners to the related DOM elements. The configuration object structure has several attributes as indicated. All of the attributes except client are optional.

1{
2    client: {},
3    signals: [],
4    selectors: {},
5    schemas: {},
6    dataProviders: {}
7}

Configuring the SDK: Client Parameters

Setting Type Description
appSourceId String Required. Obtain this value from your Salesforce admin.
beaconEndpoint String Required. Use this structure
1http://<Tenant Specific Endpoint>/web/events
.
authEndpoint String Use this structure
1http://<Tenant Specific Endpoint>/web/authentication
.
deviceId String Can also be defined in the client configuration, otherwise the identifier created and managed by the SDK is used.
sessionId String Is automatically populated by Web SDK.
consentEventTypeName String Sets the name of the Consent Event Type. The default name consentLog works for most configurations.
retryAttempts Integer Is the number of retry attempts if there are failing sending events to the beacon service.
retryDelayMS Integer Is the delay duration between retry attempts, milliseconds, if there are failing sending events to the beacon service.
automaticallyTrackNavigationEvents Boolean Enable this flag so the Web SDK automatically tracks the user page navigation events and captures document.location.hash and document.location.pathname.

Configuring the SDK: Signals

Signals are the primary part of the configuration object that the Web SDK engine uses to assign the event listeners to the appropriate DOM element on the page. Signals are the primary piece of the configuration that must be updated after initialization. The signal name, schema, and category are required fields.

1{
2    name: 'signal name',
3    schema: 'developerName of schemaEvent',
4    category: 'category', // example: engagment 
5    event: {
6      type: 'click',
7      selector: 'reference to selector name'
8    },
9    mapping: {
10      "developerName of schemaEvent field": {
11        from: 'page',
12        selector: 'css selector or reference to selector name'
13      }
14   }
15}

Calling CDP.configure method forces all registered signals on the page to be removed before the new set of signals is registered.

Note

Configuring the SDK: Signal Mapping

The mapping field for a registered signal is used to capture data from a web page and map it to the fields in the target schema set on the signal. There are two supported mapping configurations:
  • Page

    1signal: {
    2  ...
    3  mapping: {
    4    "schemaFieldDeveloperName": {
    5      from: "page",
    6      selector: "css selector or reference to selector name",
    7      scope: "event"
    8    }
    9  }
    10}

    A page mapping captures the text value of the element that matches its selector and uses that as the value for the schema event field. The scope value controls which element in the DOM is to execute the selector query. A value of event indicates the element that triggered the signal to be captured. Any other value indicates to begin at the document root.

  • Data

    1signal: {
    2  ...
    3  mapping: {
    4    "schemaFieldDeveloperName": {
    5      from: "data",
    6      provider: "dataProviderName",
    7      attribute: "attributeName"
    8    }
    9  }
    10}

    A data mapping captures the value returned by a data provider. A data provider returns a JavaScript object and the attribute value is used to map a target attribute of that object to a schema event field.

Configuring the SDK: Selectors

Every referenced selector in signal is defined here. Each selector can return one or more DOM elements. There are three types of selectors supported by the Web SDK:

  • Selectors can be composed of a CSS selector only, defining the path to a DOM element.
  • Selectors can be composed of a CSS selector and the text attribute of the last element in the path.
  • Custom JavaScript can be written to implement any unique cases where a CSS selector and text matching does not provide the required functionality.
1selectors: {
2    "unique selector name": {
3        selector: '<CSS selector (e.g. ul li.productName)>'
4    },
5    "unique selector name": {
6        selector: '<CSS selector (e.g. ul li.productName)>',
7        containsText: "<Text pattern to match inside the DOM Element(s).>"
8    },
9    "unique selector name": {
10        selector: function() {
11            // Creating a dynamic selector based on data from the page's data layer
12            return document.getElementById("product_" + dataLayer.get('currentProductId'));
13        }
14    }
15}

Configuring the SDK: Schemas

Export your schemas and load them into the SDK.

1schemas: {
2    schemaId: {
3      ...  
4    }
5  }

Configuring the SDK: Data Providers

Data providers represent information that cannot be captured directly from on-screen elements. They are functions that return JavaScript objects from a data layer. The function passes a domEvent parameter that contains the event that triggered this signal to be processed.

1dataProviders: {
2        functionName (domEvent) {
3            return <data based on the input param>
4        }
5    }

Sample Configuration Object

1{
2    signals: [
3        {
4            name: 'Remove from cart button',
5            category: "Engagement",
6            schema: 'RemoveFromCart',
7            event: {
8                type: 'click',
9                selector: "remove from cart button selector"
10            },
11            providers: [
12                'productCatalog'
13            ],
14            mapping: {
15                ProductId: {
16                    from: 'data',
17                    provider: 'productCatalog',
18                    attribute: 'ProductId'
19                },
20                ShoppingCartId: {
21                    from: 'data',
22                    provider: 'productCatalog',
23                    attribute: 'ShoppingCartId'
24                }
25            }
26        },
27        {
28            name: 'Add to cart button',
29            schema: 'AddToCart',
30            category: "Engagement",
31            event: {
32                type: 'click',
33                selector: "add to cart button selector"
34            },
35            providers: [
36                'productCatalog'
37            ],
38            mapping: {
39                ProductId: {
40                    from: 'data',
41                    provider: 'productCatalog',
42                    attribute: 'ProductId'
43                },
44                ShoppingCartId: {
45                    from: 'data',
46                    provider: 'productCatalog',
47                    attribute: 'ShoppingCartId'
48                }
49            }
50        },
51        {
52            name: 'Username typed',
53            schema: 'usernameTyped',
54            category: 'Profile',
55            event: {
56                type: 'keydown',
57                selector: "username textbox"
58            },
59            mapping: {
60                username: {
61                    from: 'page',
62                    selector: "username textbox",
63                    scope: 'document'
64                }
65            }
66        },
67        {
68            name: 'Product click',
69            schema: 'ProductViewed',
70            category: "Engagement",
71            event: {
72                type: 'click',
73                selector: "product selectors"
74            },
75            providers: [
76                'productCatalog'
77            ],
78            mapping: {
79                ProductId: {
80                    from: 'data',
81                    provider: 'productCatalog',
82                    attribute: 'ProductId'
83                }
84            }
85        },
86        {
87            name: 'opt-in',
88            schema: 'consent-opt-in',
89            category: "Consent",
90            event: {
91                type: 'click',
92                selector: "consent opt-in selector"
93            }
94        },
95        {
96            name: 'opt-out',
97            schema: 'consent-opt-out',
98            category: "Consent",
99            event: {
100                type: 'click',
101                selector: "consent opt-out selector"
102            }
103        }
104    ],
105    dataProviders: {
106        productCatalog (domEvent) {
107            return {
108                "ProductId": "product-id-9aba47743f27",
109                "ShoppingCartId": "shopping-cart-id-9aba47743f27"
110            }
111        }
112    },
113    selectors: {
114        "remove from cart button selector": {
115            selector: 'body > div.wrapper.svelte-1a3asx9 > main > div > div.slds-col.slds-size_2-of-3 > div:nth-child(3) > div:nth-child(2) > div:nth-child(6) > button:nth-child(2)'
116        },
117        "add to cart button selector": {
118            selector: 'button.slds-button.slds-button_destructive',
119            containsText: "ADD"
120        },
121        "product selectors": {
122            selector: function() {
123                return document.querySelectorAll('.stencil');
124            }
125        },
126        "consent opt-in selector": {
127            selector: '#dialog-body-id-42 > a > div > p > button.slds-button.slds-button_brand'
128        },
129        "consent opt-out selector": {
130            selector: '#dialog-body-id-42 > a > div > p > button.slds-button.slds-button_destructive'
131        },
132        "username textbox": {
133            selector: '#username'
134        }
135    }
136}

Initializing the SDK

The first step in the lifecycle of the SDK on a page is for it to be initialized. This initialization is where parameters, like the Source ID from the Website Connector, is set to the appSourceId, and the auth and beacon endpoints, crafted from the tenant-specific endpoint, are passed into the SDK.
1window.addEventListener('load', (event) => {
2   const CONFIG = {
3       client: {
4           "appSourceId": "app source id as guid",
5           "deviceId": "deviceId as guid", // optional
6           "beaconEndpoint": "http://server.internal:8080/web/events",
7           "authEndpoint": "http://server.internal:8080/web/authentication"
8       }
9   };
10   CDP.initialize(CONFIG);
11});
  • CDP.initialize(CONFIG) - configures the SDK on initial load, client configuration required
  • CDP.register(CONFIG) - updates, creates, and overrides configuration parameters

Grab Parameters from the Url

A common operation for user tracking code within a website is to grab the value from query parameters that were passed in the URL. The Customer Data Platform Web SDK includes the following get function that grabs parameters from a web address.

1CDP.getUrlParam('trackingId')

Send Events

Sending signals from your website back to Customer Data Platform is the primary function of the Customer Data Platform Web SDK. The sendEvent() method hides most of the behind-the-scenes complexity and allows you to focus on collecting the data you want to send, without dealing with the mechanics of authentication, building payloads, and managing connections. Your send events must match your schema.
1CDP.sendEvent("engagement", "ProductView", productData)

In this example, a product view engagement event is being sent. The product data can come from the DOM, data objects, URL parameters, or any combination of those sources. The required fields for all Customer Data Platform events are populated by the SDK and combined with the provided event data.

By default, the SDK sends events with GET, but if the event payload exceeds 1024 characters a POST with the content type of application/x-www-form-urlencoded is performed instead.

Manage Consent

The Customer Data Platform Web SDK doesn’t persist consent settings across sessions. Pass consent settings for each site visitor. This configuration allows the SDK to integrate easily with existing consent management solutions on your website.

Use these functions in callbacks from your consent management system. The cookie stored by the SDK can't be used to manage consent for your website. The SDK only checks if consent has been granted before sending events.

1CDP.consentOptIn();

This call grants consent to the SDK to allow events to signal triggered actions. It sends the CDP.consentOptIn(); event and creates a cookie signifying the user opted in. On subsequent page loads, the presence of this cookie allows events to begin transmitting immediately.

1CDP.consentOptOut();

This call removes consent, stops events from being sent. The cookie is removed and events stop emitting immediately.