Commanders Act X
Platform XDocumentationWelcome to Success
  • Welcome !
  • Platform updates
    • Announcements
    • Documentation updates
    • Release notes
  • Getting started
    • How the platform works
      • Glossary
        • Condensed platform concepts
    • Platform interface
      • Prod and Testing environments
      • Productivity tools
        • Commander's AI
    • Integrating your data
      • GTM Tutorial
      • OneTag Tutorial
      • Migration guides to the Platform X
        • Migrate from SSv1 to SSv2
          • Send data to serverside v2
            • Purchase event example (ssv1 to ssv2)
        • Migrate from old mobile sdk
  • Features
    • Sources
      • Sources Overview
      • Sources Catalog
        • Web
          • Web container
            • User guides for browser-side platform
              • Container
                • Hosting
                • Creation and modification
                • Generation
                • Testing
                • Deployment and roll back
                • Deletion
                • Statistics
                • Modification history
                • Javascript block
                • Branches
                • Plugin Commanders Act Assistant
              • Tags
                • Add tags
                • Configure tags
                • Rules
                  • Basic actions
                  • Triggers
                  • Perimeters & constraints
              • Data layer and data types
                • External variables
                • Internal variables
                • Event variables
                • Data storage
              • Deduplication
                • Setup guide
                • Setup example
                • Deduplication reports
              • TagPerformance
                • Setup guide
                • Report analysis
                • Troubleshooting
            • Setup guides for developers
              • Web container setup
              • Datalayer setup
              • Browser-side events setup
              • AMP
              • Angular
              • AngularJS
              • React
              • SPA implementation guide
              • VueJS
              • IOT & TV Apps
            • Best Practices
              • FAQ
              • Common Container Strategies
              • Common Trigger Strategies
              • Performance Optimization
              • tC.* attributes and methods
              • APIs
                • Onsite API
              • TMS & Consent banners IDs
          • Javascript SDK
            • Next.js serverside rendering
          • Pixel Tracking API
          • Google Tag Manager (GTM)
          • Shopify
        • Mobile APP
          • Android
          • iOS
          • Flutter
          • React native
        • Advertising
          • Bing Ads (cost import)
          • Facebook Ads (cost import)
          • Criteo (cost import)
          • Realytics
        • Import CRM users
          • API users
          • Users file importer
        • Import conversions
          • API Conversions and Product catalog
          • Conversions files importer
        • Product catalog
          • Product catalog files importer (FTP)
        • Server
          • HTTP tracking API source
            • (deprecated) HTTP tracking API source 1.0
          • Node.JS
          • Python
          • PHP
      • Source Live Event Inspector
      • Source data quality
    • Destinations
      • Destinations overview
        • Automatic Audience replay
      • Destinations catalog
        • AbTasty
        • Actito
        • Adform
        • Adobe
          • Adobe Analytics
          • Adobe Campaign
        • AdRoll
        • Adition
        • Adventori
        • Affilae
        • Alphalyr Marketing Studio
        • Amazon
          • Amazon Ads Conversions API
          • Amazon S3
        • Attraqt
        • Awin
        • Batch Audience
        • Branch Events
        • Button
        • Campaign Analysis Legacy
        • Commission Junction
        • Criteo
          • Criteo - Events
          • Criteo (audiences)
          • Criteo (offline conversions)
        • Data Activation Legacy
        • Dataventure
        • Destination Logs Exporter (closed beta)
        • Dialog-Mail
        • Dynamic Yield
        • Easyence
        • Effinity
        • Eloqua
        • Emarsys
        • Email export
        • Equativ Audience
        • Experian
        • Facebook
          • Facebook Conversions API
            • Facebook CAPI through GTM
            • Performance tab (Event Match Quality)
          • Facebook Custom Audiences
          • Facebook Lead Ads
        • FTP
        • Gamned
        • Google
          • Google Analytics 4
            • Google Analytics 4 - Proxy Mode
          • Google BigQuery
          • Google Conversion Adjustments
          • Google Customer Match
          • Google Display & Video 360
          • Google Enhanced Conversions
          • Google Enhanced Conversions for Leads
          • Google Floodlight Mobile App Conversion
          • Google Search Ads 360 Enhanced Conversions
          • Google Store Sales Direct
        • IBM
        • Inxmail
        • IntelliAd
        • Jellyfish
        • Kameleoon
          • Kameleoon Audience
          • Kameleoon Events
        • Kelkoo
        • Kwanko
        • LinkedIn Conversions API
        • Liveramp
        • Magento
        • Marin Software
        • Mapp
        • Matomo
        • MediaMath
        • Microsoft Advertising Universal Event Tracking
        • Mindlytix
        • Moebel
        • Nextdoor Conversion API
        • OXID
        • Optimizely
        • Outbrain
        • Partnerize
        • Piano Analytics
          • Piano Analytics Collection API
          • Piano Analytics Enrichment API
        • Pinterest
        • Piwik PRO
        • Prediggo
        • Qlik
        • Quantcast
        • Quora Ads Conversion API
        • Rakuten
          • Rakuten Audience
          • Rakuten Events
        • Realytics
        • Reddit Conversions API
        • Responsys
        • RhythmOne
        • Rich Relevance
        • RTB House Audience
        • Salesforce
          • Salesforce Audience Studio
          • Salesforce Marketing Cloud
          • Salesforce Commerce Cloud
        • SAP Commerce Cloud
        • Selligent
        • Skai
        • Smart Adserver
        • SmartFocus
        • Snapchat Conversions API
        • Splio
        • Syte
        • Tableau Online
        • Taboola
          • Taboola Audience
          • Taboola Events
        • Target2sell
        • Temelio
        • Teradata
        • The Trade Desk
          • The Trade Desk Conversions API
          • The Trade Desk Audience
        • TikTok
          • TikTok Events API
          • TikTok Offline Events
        • TimeOne
        • Tradedoubler
        • TradeTracker
        • X (Twitter) Conversion API
        • Xandr
        • Webhook
        • Webtrends
        • ZBO Media
        • Zeta
      • Destination builder
        • Javascript destination builder
          • Tutorial - How to build a server destination with the JS sandbox
          • Serverside javascript helpers
      • Destination filters
      • Mapping and Properties transformation
      • Event delivery
      • Destination event inspector
      • Dry mode (lab)
    • Enrichments
      • Augmented User Attributes
        • Business case
      • Events enrichment
      • Storage Settings
    • Data Quality
      • Event Specification
      • Sources data quality
      • Data cleansing
        • Supported transformation functions - Data cleansing
          • Format a date
    • Identity resolution
      • Migrate from Fuse v1 to Fuse v2
    • Customers
      • Segment
        • Segment overlap
        • Segment stats
    • Explore
      • Campaign analysis
        • Attribution
        • Control Group (Closed Beta )
      • User analysis
        • Dashboards
      • Consent Analysis
    • Consent management
      • Responsability of actors
      • Setup Guides
        • Tag Manager
          • Commanders Act TMS
          • Google Tag Manager (GTM)
          • Google Tag Manager (GTM) - Consent Mode
          • Google Consent Mode in Commanders Act CMP
          • Adobe Launch
        • Websites (Hardcoded)
        • FR : Suppression des cookies lors du retrait du consentement
        • Mobile apps
          • iOS
            • ATT - App Tracking Transparency (iOS 14.5+)
          • Android
      • User Guides
        • Categories & Tags
          • Manage Categories
          • Manage Vendors
          • Assign Categories
        • Privacy Banners
          • Banner Templates
            • Accessibility Template
          • Manage Banner
          • Deploy Banner
          • Copy Banner
        • Consent Analysis
        • Exports
        • Settings
      • Extensions
        • Cookie Scanner
        • Piggybacking
        • Tag Firewall
      • Marketing Preferences Center (additional module)
      • Knowledge Base
        • Consent Object
        • Consent cookies exemption
          • Implementation guide for exempted consent statistics FR market
        • Consent Cookie
        • IAB TCF V2.2 Release details
          • IAB TCF v2.2 CMP requirements
          • IAB TCF v2.2 Migration guide Web
          • IAB TCF v2.2 Migration guide App
        • IAB TCF V2.2 Consent
        • IAB TCF V2.2 and Google FAQ
        • Google ACM requires IAB TCF
        • CCPA & Global Privacy control
      • Rest Data API
        • GET/PUT Consents / preferences
      • OnSite API
        • Getting Started
        • consent.get
        • consent.update
        • consent.revoke
        • consent.onUpdate
        • consent.onReady
        • consentBanner.show
        • consentBanner.hide
        • consentCenter.show
        • consentCenter.hide
      • Platform API
        • Get statistics
  • Use cases
    • Data activation
      • Engage new customers
        • Welcome banner for new customers
        • Real-time promotion for hesitant customers
        • Discount banner for installing the application
        • Personalized ads
        • Engage similar audience (lookalike)
      • Increase loyalty
        • Drive to favourite store
        • Increase Customer Lifetime Value with a loyalty program
        • Notification about order delay
      • Increase revenue
        • Abandoned cart
        • Products recommendations
        • Complementary product offer
      • Retain customers
        • Identify a churn risk with RFM segmentation
        • Identify customers’ preferred channel
        • Contact with the customer support
      • Advocacy
        • Incentive to share customers' experience and rating
        • Sponsorship Program
        • Social Media Hashtag
    • Website performance
    • Consent banners A/B testing
    • Customer analysis
    • Campaigns performance analysis
  • Developers
    • Tracking & Integrations
      • Tracking
        • About events
          • E-commerce/retail events
          • Web event specificity
          • Mobile App event specificity
        • Events reference
          • Common events
          • E-commerce events
          • Video events
          • Campaign Tracking events
        • Properties reference
          • Global properties
          • Video properties
          • Permanent properties
        • Data API
          • HTTP API
          • Segment API
          • User API
          • Product catalog and conversion API
      • Server IP Whitelisting
    • Config API
    • Changelogs
      • Measure.js changelog
      • Web container generator
    • Content Security Policy
  • CONFIGURE
    • Data Management
      • Events collection
      • Data retention duration
      • Data Governance
    • Administration
      • User management
      • Domain Management
        • WAF Proxy (CloudFlare,...)
        • A record
        • CNAME record
        • On-Premise Proxy
        • Cookie CAID
        • First party hosting
      • Single Sign-On
      • Two-factor authentication (2FA)
      • Copy Management
    • Cookies
      • Cookie 1st
      • Cookie sync partners
      • First domain tracking (Phoenix)
    • Disclaimer
Powered by GitBook
On this page
  • Getting Started
  • How to use
  • Initialize global settings with config
  • Send event
  • Get information
  • Error handling
  • Meta Properties
  • API Stub (optional)
  • Use Javascript SDK in TMS
  • Browser-Side Events
  • Available Events
  • Listening to all Events
  • Custom Tag Triggers
  • Commands Reference
  • Tag Context Variables
  • Best Practices and Tips

Was this helpful?

Edit on GitHub
Export as PDF
  1. Features
  2. Sources
  3. Sources Catalog
  4. Web

Javascript SDK

PreviousTMS & Consent banners IDsNextNext.js serverside rendering

Last updated 10 months ago

Was this helpful?

Getting Started

The onsite API is used to interact with Commanders Act features with JavaScript.

There are different commands available within cact(): config is used to set general options, trigger event is used to send data, and other specific get/update/revoke commands are used to interract with platform features (ex : get user consent)

To use the API, you must have either a web container on the page or the JS SDK library script:

How to use

The onsite API consists of a single function, cact(), with the following strict signature:

cact(command, [options,], [config,], [callback])
Argument
Descriptions
Required

command

A string identifier used to select the desired method.

Required

options

A JavaScript object that includes data passed to the method.

Optional

config

A javascript object that is used to override the default settings like siteId , collectionDomain , eventId, or sourceKey

Optional

callback

A JavaScript callback function that is used to receive information or events from the onsite API.

Optional

Onsite API is included in each containers and privacy banners.

Initialize global settings with config

Use the config command to initialize and configure settings for a particular workspace.

This command is optional, you can also set custom settings directly inside a, through the config object parameter.

The config command takes the following format:

cact('config', {<config_object>});

Config object accept 4 parameters, they are optional if you use a web container on your page :

  • siteId : if not set, the default value is the site id of the last web container loaded (tC.id_site)

  • sourceKey: if not set, the default value is derivative from you web container id. If you don't have a web container, the sourceKey is mandatory and correspond to your JS SDK source.

  • eventId: if not set, an random id is set for this event and will be put in context.event_id

Example :

cact('config', { siteId: 1234, sourceKey: 'abcd' });

Send event

To send event data to the serverside Commanders Act platform, use this command:

cact('trigger', '<event_name>', {<event_params>});

Example : to send a purchase event :

cact('trigger', 'purchase', {   id:'1234',  currency: 'EUR',  //...});

Example : to send a purchase event, overriding the default tracking domain / workspace / sourcekey :

cact('trigger', 'purchase', {   id:'1234',  currency: 'EUR',  //...},{
    collectionDomain: "my.firstdomain.com",
    siteId: "1234", 
    sourceKey: "abcd"
});

Get information

To get various values from Commanders Act, use this command:

cact(get command, [callback])

Example : to get consent from TrustCommander, you can call the consent.get API like this:

cact('consent.get', function(result) {    if (result.consent.status === "all-on") {                // Consent available for all categories.            }});

The onsite API methods are called asynchronously. In case e.g. you need information synchronous in the <head> of the document it is recommended to cache and retrieve the result of the API in localStorage.

Error handling

You can handle errors through error property in the callback object. Example:

cact('consent.get', function(result) {​    if (result.error) {            // Manage the error        }    else if (result.consent.status === "all-on") {                // Consent available for all categories.            }});

Meta Properties

API Stub (optional)

For advance usage, we provide also an API stub that can be added when you need to interact with the API before containers or banners have loaded. This stub is already included in containers and privacy banners, so you do not have to add in most use cases. The stub is used to buffer all methods in a JavaScript array until Commanders Act JavaScript is loaded and ready to process the methods. This allows for example to use the onsite API before TrustCommander JavaScript was loaded.

window.caReady = window.caReady || []; window.cact = function() { window.caReady.push(arguments); };

window.caReady is a JavaScript array that buffers the interactions with the API. window.cact is a JavaScript function used to interact with the onsite API.

In case you work in a big team and are unsure the stub was already installed it is ok to install the JavaScript stub multiple times.

Use Javascript SDK in TMS


Our system now includes several new and improved features to help you efficiently manage and implement tags on your website. This guide provides comprehensive information on using our TMS webcontainers and JavaScript SDK, including browser-side events, command references, and tag context variables.


Browser-Side Events

Introduction

Our new cact('emit') API is a new approach of tC.event.XXX functions, ensuring safer and more reliable event handling.

Here’s how you can use these events:

<!-- Old method (may cause issues if event does not exist) -->
<a href="mysite.com" onclick="tC.event.my_custom_event(this, { my_event_variable: 'some_value' });">

<!-- New method (safe) -->
<a href="mysite.com" onclick="cact('emit', 'my_custom_event', { from: this, my_event_variable: 'some_value' });">

Note that hyphens (-) in event names will be converted to underscores (_). For example, cact('emit', 'my-custom-event') will actually call tC.event.my_custom_event.

Available Events

  • container_ready: Fires for every loaded container.

  • container_<siteId>_<containerId>_ready: Fires a specific event for each containercontainer_ready event (ex: container_1234_1_ready)

  • consent-ready: Fires when the consent cookie is set or the banner is accepted/refused.

  • consent-updated: Fires when consent is updated.

  • consent-revoke: Fires when consent is revoked.

  • consent-signal-ready: Used for Google Consent Mode setups.

  • banner-show: Fires when the privacy banner is shown.

  • banner-hide: Fires when the privacy banner is hidden.

  • privacy-center-show: Fires when the privacy center is shown.

  • privacy-center-hide: Fires when the privacy center is closed.

  • tag_trigger_form_submission: Standard form trigger.

  • tag_trigger_clicks: Standard clicks trigger.

  • tag_trigger_scroll: Standard scroll trigger.

  • track_all_events: Server-side event sent with cact('trigger') API.

  • track_*: Similar to track_all_events but with specific event names (e.g., track_page_view, track_add_to_cart).

  • privacy-module-loaded: Internal event fired when tC.privacy is initialized.

  • Custom events: Sent using cact('emit').

Trigger example to fire a tag on consent-update event

Listening to all Events

You can listen to all events using the cact('on', '*') API.

function listen_all_events(event) {
  console.log(event.type); // '*'
  console.log(event.originalEvent.type); // 'page_view'
}

cact('on', '*', listen_all_events);
cact('emit', 'page_view');

Custom Tag Triggers

To fire a custom trigger, use the cact('emit', 'my_custom_event') command. Note that hyphens will be converted to underscores when launching the trigger.

cact('emit', 'my_custom_event');

You will be able to use this event as a TMS custom trigger:


Commands Reference

The container provides a set of commands, some of which trigger browser-side events. To see all commands, type tC.cact in your console.

config

Set various website configurations.

cact('config', { siteId: 4242, collectionDomain: 'example.com', sourceKey: 'ABCD-1234-EFGH' });

setProperty

Set properties to be merged with server-side events sent via the trigger API.

cact('setProperty', 'page_type', 'homepage');
cact('setProperty', 'user.email', 'user@example.com');

emit (Alias: dispatchEvent)

Dispatch a browser-side event for use as a custom tag trigger.

cact('emit', 'page_view', { page_type: 'homepage' });

on (Alias: addEventListener)

Subscribe to a browser-side event.

cact('on', 'page_view', function(event) {
  console.log('event received of type', event.type); // 'page_view'
  console.log('event data is:', event.eventData); // { page_type: 'homepage' }
});

cact('emit', 'page_view', { page_type: 'homepage' });

once

Similar to on, but the callback fires only once.

cact('once', 'page_view', listener_callback);

off (Alias: removeEventListener)

Remove an event listener.

cact('off', 'page_view', listener_callback);

trigger

Send a server-side event. Any call to cact('trigger', ...) will also dispatch a generic track_all_events event.

cact('trigger', 'add_to_cart', { value: 42, currency: 'EUR' });


Tag Context Variables

The Tag Context provides variables used within a tag. If you need a Tag Context similar to "Container Loaded," consider using the container_ready custom trigger.

cact_container

Contains information about the container.

{
  id_container: <containerId>,
  id_site: <siteId>,
  sourceKey: <sourceKey>
}

cact_event

The event that triggered the tag, with a property cact_event.type.

cact('emit', 'page_view', {});
// cact_event.type will be 'page_view'

cact_event_vars

Contains all event variables from the trigger.

cact('emit', 'page_view', { hello: 'world' });
// cact_event_vars will be { hello: 'world' }

cact_event_attrs

Contains event attributes, set using the from property in emit or trigger API.

<a href="/home" onclick="cact('emit', 'page_view', { from: this, hello: 'world' })">Home</a>

For more examples and a live demo, refer to the documentation links provided.


Best Practices and Tips

Resolving Site-ID/Source-Key Conflicts

In multi-container websites, events were sometimes sent with incorrect site-id or source-key. This issue is fixed for tags using triggers other than native "Container Loaded." Use the new container_ready custom trigger for accurate site-id/source-key resolution.

Privacy-Related Events

You can use various privacy-related events as custom triggers:

  • consent_ready

  • consent_updated

  • consent_revoke

  • banner_show

  • banner_hide

  • privacy_center_show

  • privacy_center_hide

Server-Side Tracking as Custom Triggers

Need to track an event sent in Server Side ?

Our cact('trigger', ...) will dispatch a corresponding track_* event, that you can use as a custom trigger.

cact('trigger', 'page_view', { value: 42, currency: 'EUR' });

To use this feature as a TMS custom tag trigger, you'll need to prefix the event name with "track_*" Example:

Using cact('on') for Event Subscription

You can subscribe to any event sent using cact('emit').

cact('on', 'my_custom_event', function(event) {
  console.log('received an event', event.type); // "my_custom_event"
  console.log('event data:', event.eventData); // { var: "value" }
});

collectionDomain: if not set, the default value is collect.commander1.com (or your first party domain, if you setup one and use a )

To use the API, you must have either a web container on the page or the JS SDK library script :

The meta property includes metadata and context for the consent that was provided on a browser. You can see the list of Meta properties

web container
https://cdn.tagcommander.com/events/sdk.js
https://cdn.tagcommander.com/events/sdk.js
trigger command
here