The Main Tracking Tag

The Contentsquare Main Tracking Tag or Main tag is the core ‘pixel’ or ‘code snippet’ that needs to be implemented on your domain in order to collect analytics data. It can be implemented through a Tag Management System (TMS) or on the site’s template. Find step-by-step guides below.

Prior to the implementation, you need to gather the following information:

  • A Contentsquare Tag ID will be provided after kicking off the Contentsquare partnership. This 13-character unique ID can be use only on agreed domains — no data will be sent from elsewhere.

  • You can provide up to 20 custom variables to enrich the analysis context with details about the pages or the user. They’re usually collected from your datalayer or any other JavaScript object implemented throughout the site.

  1. Open your container and go to the templates section.

  2. Select Search gallery.

  3. Type in contentsquare and select the Contentsquare - Main tag option.

  4. Click Add to workspace.

  5. Confirm your choice by selecting Add

  6. Go to the Tags section and click the New button to create a new tag.

  7. Configure it by selecting the top-right button.

  8. Search for contentsquare and select the Contentsquare - Main tag template that you’ve previously added to your container.

  9. Give a title to the tag and input your Tag ID in the dedicated field. To configure Custom Variables, enter:

    • The index, from 1 to 20 - unique numbers only.
    • The name.
    • The value itself, which will be taken from one of your GTM Variables.
    • The scope — select Page & Visit (2 & 3), or Single Page App (nextPageOnly 4) if your website/part of it is a Single Page Application. Check with Contentsquare contact if unsure.
  10. Select the trigger: All Pages or DOM Ready (when data layer has been fully loaded). We suggest All Pages, as long as your selected variables will be populated by then.

  11. (Optional) Mask Personal Data within the GTM GUI.

    Select the appropriate Personal Data masking method, depending on the type of personal information you’re looking to mask:

    • Define CSS Selectors for text nodes.
    • CSS Selectors and Data Attributes for element attributes.
  12. Save your changes and go back to your container. You should now see both the template and the newly created tag.

Google Tag Manager (Custom HTML)

Section titled Google Tag Manager (Custom HTML)
  1. Add a new tag on your workspace.

  2. Select “Choose a tag type to begin setup…”.

  3. In the list, pick the “Custom HTML” tag.

  4. Depending on your data layer availability, take a look at the following code examples and populate it with the information required:

    • Implementing the tag and pushing data layer variables to Contentsquare:

      <script>
      (function () {
      window._uxa = window._uxa || [];
      try {
      window._uxa.push(['setCustomVariable', 1, 'Sample Variable', {{your-GTM-variable-here}}, 3]);
      } catch(e){}
      if (typeof CS_CONF === 'undefined') {
      window._uxa.push(['setPath', window.location.pathname+window.location.hash.replace('#','?__')]);
      var mt = document.createElement('script'); mt.type = 'text/javascript'; mt.async = true;
      mt.src = '//t.contentsquare.net/uxa/{{YOUR_TAG_ID}}.js';
      document.getElementsByTagName('head')[0].appendChild(mt);
      }
      else {
      window._uxa.push(['trackPageview', window.location.pathname+window.location.hash.replace('#','?__')]);
      }
      })();
      </script>
    • Implementing the tag without pushing data layer variables to Contentsquare:

      <script>
      (function () {
      window._uxa = window._uxa || [];
      if (typeof CS_CONF === 'undefined') {
      window._uxa.push(['setPath', window.location.pathname+window.location.hash.replace('#','?__')]);
      var mt = document.createElement('script'); mt.type = 'text/javascript'; mt.async = true;
      mt.src = '//t.contentsquare.net/uxa/{{YOUR_TAG_ID}}.js';
      document.getElementsByTagName('head')[0].appendChild(mt);
      }
      else {
      window._uxa.push(['trackPageview', window.location.pathname+window.location.hash.replace('#','?__')]);
      }
      })();
      </script>

  5. Select “Choose a trigger to make this tag fire…”.

  6. In the list, pick the “All pages” trigger, provided the Datalayer will have been loaded before firing our tag.

  7. Name your tag (for instance Contentsquare Main Tag), then click “Save”.

  1. Add a new tag to your containers by choosing “Content Square UX Analytics ”

  2. Add your “TAG ID” and click “next” twice, keeping the default configuration. If you do not have custom variables, click “Finish” and the installation is over.

  3. (Optional) Add custom variables:

    • Choose a datalayer Variable in the UDO list and select Select Destination
    • Select “Custom”
    • Add a variable Name
    • Click Add
    • Click Close and the mapped variable will appear

  4. Click “Finish” or repeat STEP 3 for additional variables.

Installing the Contentsquare extension

Section titled Installing the Contentsquare extension
  1. Search for Contentsquare within Extensions and select Install.

  2. Enter your Tag ID (should be provided by your Contentsquare Implementation team).

    To pass information to Contentsquare via custom variables, select Add a custom variable and fill the following fields:

    • The index, from 1 to 20 - unique numbers only.
    • The name.
    • The value itself, which will be taken from one of your GTM Variables.
    • The scope — select Page & Visit (2 & 3), or Single Page App (nextPageOnly 4) if your website/part of it is a Single Page Application. Check with Contentsquare contact if unsure.

    Use Data Elements in the value fields, as they are the Launch built-in method of passing information between extensions.

  1. (Optional) Select Add PII Masking.

  2. Upon activating Personal Data Masking, select the appropriate masking method, depending on the type of personal information you’re looking to mask:

    • Masking textual Personal Data using CSS selectors: Make sure that your CSS selectors are valid.

    • If non-textual personal information needs to be masked, use the below text box and template:

  3. Save your changes to your working library and move to the next step.

Navigate to Rules, and open an existing rule or create a new one.

Depending on your needs, select the event to be used from the Core extension.

Take a look at some of the viable examples below:

Select the Main Tracking Tag Installation action from the Contentsquare extension

If you don’t need to further amend the path or the queries sent, you can leave the action as it is and press ‘Keep Changes’

Should you need to override the path or the query, you can do so by selecting the element and writing the string to be used as a substitute. You can also create Data Elements and use them in these fields

Once you’re done, your new rule should look similar to the following

You can now press save and move on to the next rule.

  1. Add a new tag to your containers by choosing “Contentsquare - Tag Main (builder)”.

  2. Add your previously provided Tag ID.

  3. Add the desired Custom Variables:

    • At “Add customs variables” select “yes”
    • Fill all request variables by add a name and pick the matching variable from the datalayer.

The Contentsquare Main Tag is ready to be deployed.

  1. Within the main menu, select Online Store > Themes, then click the Actions drop-down menu, and Edit Code.

  2. Under Layout, select the theme.liquid file.

  3. Within the code editor, scroll down to the closing </head> tag.

  4. Copy the code below and replace YOUR_TAG_ID with your Contentsquare Tag ID:

    <!-- Contentsquare Tags Start -->
    <script type="text/javascript">
    // Contentsquare Main Tracking Tag
    (function() {
    window._uxa = window._uxa || [];
    if (typeof CS_CONF === 'undefined') {
    window._uxa.push(['setPath', window.location.pathname + window.location.hash.replace('#', '?__')]);
    var mt = document.createElement("script");
    mt.type = "text/javascript";
    mt.async = true;
    mt.src = "//t.contentsquare.net/uxa/YOUR_TAG_ID.js";
    document.getElementsByTagName("head")[0].appendChild(mt);
    } else {
    window._uxa.push(['trackPageview', window.location.pathname + window.location.hash.replace('#', '?__')]);
    }
    })();
    </script>
    <!-- Contentsquare Tags End -->
  5. Paste the code above the closing </head> tag.

  6. Click Save.

Track the Checkout flow with Contentsquare

Section titled Track the Checkout flow with Contentsquare

Tracking the Checkout flow is done via a custom pixel to add to your Shopify checkout.
This custom pixel allows for sending a pageview and a dynamic variable to Contentsquare within each step of the checkout, for mapping and segmentation purposes, and track ecommerce transactions, all in one script.

This solution works for both single page and multi-step checkout scenarios.

Events collected are:

  • checkout_started
  • checkout_contact_info_submitted
  • checkout_address_info_submitted
  • checkout_shipping_info_submitted
  • payment_info_submitted
  • checkout_completed
  • Ecommerce data:
    • orderID
    • amount
    • currency

Once collected, these events are available for segmentation and filtering:

Adding the custom pixel to your checkout

Section titled Adding the custom pixel to your checkout
  1. Select Settings in the Shopify admin section.

  2. Select Customer events then Add custom pixel.

  3. Enter a name for the pixel such as Contentsquare Checkout.

  4. Copy and paste the code below and replace {{YOUR_TAG_ID}} with your Contentsquare Tag ID:

    /*
    *Name: Shopify CS Integration
    *Version: 2.2.0
    */
    const csTagID = "{{YOUR_TAG_ID}}";
    const csTypeVendorPrefix = "CMS_SH_";
    let submittedEvents = [];
    function sendToCS(csKey, csValue, csPV, eventContext) {
    csKey = csTypeVendorPrefix + csKey;
    setTimeout(function () {
    let setQuery;
    if (csPV && eventContext) {
    const hash = eventContext.window.location.hash;
    const query = eventContext.window.location.search;
    setQuery = "?" + csPV;
    if (hash) {
    setQuery = hash.replace("#", "?__") + csPV;
    } else {
    if (query) {
    setQuery = "?__" + csPV;
    }
    }
    }
    _uxa.push(["trackPageview", eventContext.window.location.pathname + setQuery]);
    _uxa.push([
    "trackDynamicVariable",
    {
    key: csKey,
    value: csValue,
    },
    ]);
    }, 500);
    }
    function sendEcomCS(orderID, amount, currency) {
    _uxa.push([
    "ec:transaction:create",
    {
    id: orderID,
    revenue: amount,
    currency: currency,
    },
    ]);
    _uxa.push(["ec:transaction:send"]);
    }
    analytics.subscribe("page_viewed", (event) => {
    if (event.context.window.location.pathname.indexOf("/checkouts") > -1 && event.context.window.location.pathname.indexOf("/processing") === -1) {
    if (typeof CS_CONF === "undefined") {
    window._uxa = window._uxa || [];
    _uxa.push(["setPath", event.context.window.location.pathname + event.context.window.location.hash.replace("#", "?__")]);
    const mt = document.createElement("script");
    mt.type = "text/javascript";
    mt.async = true;
    mt.src = "//t.contentsquare.net/uxa/" + csTagID + ".js";
    document.getElementsByTagName("head")[0].appendChild(mt);
    } else {
    _uxa.push(["trackPageview", event.context.window.location.pathname + event.context.window.location.hash.replace("#", "?__")]);
    }
    }
    });
    analytics.subscribe("checkout_started", (event) => {
    if (!submittedEvents.includes(event.name)) {
    submittedEvents.push(event.name);
    sendToCS("Checkout Started", "true", event.name, event.context);
    }
    });
    analytics.subscribe("checkout_contact_info_submitted", (event) => {
    if (!submittedEvents.includes(event.name)) {
    submittedEvents.push(event.name);
    sendToCS("Checkout Contact Info Submitted", "true", event.name, event.context);
    }
    });
    analytics.subscribe("checkout_address_info_submitted", (event) => {
    if (!submittedEvents.includes(event.name)) {
    submittedEvents.push(event.name);
    sendToCS("Checkout Address Info Submitted", "true", event.name, event.context);
    }
    });
    analytics.subscribe("payment_info_submitted", (event) => {
    if (!submittedEvents.includes(event.name)) {
    submittedEvents.push(event.name);
    sendToCS("Payment Info Submitted", "true", event.name, event.context);
    }
    });
    analytics.subscribe("checkout_shipping_info_submitted", (event) => {
    if (!submittedEvents.includes(event.name)) {
    submittedEvents.push(event.name);
    sendToCS("Checkout Shipping Info Submitted", "true", event.name, event.context);
    }
    });
    analytics.subscribe("checkout_completed", (event) => {
    if (!submittedEvents.includes(event.name)) {
    submittedEvents.push(event.name);
    sendToCS("Checkout Completed", "true", event.name, event.context);
    const data = event.data || "";
    const checkout = data.checkout || "";
    const order = checkout.order || "";
    const orderID = order.id;
    const totalPrice = checkout.totalPrice || "";
    const amount = totalPrice.amount;
    const currency = totalPrice.currencyCode;
    if (typeof orderID != "undefined" && typeof amount != "undefined" && typeof currency != "undefined") {
    sendEcomCS(orderID, amount, currency);
    }
    }
    });
  5. Select Save then Connect.

  6. Test that pageviews are sent in the checkout. Make a transaction to test the ecommerce transaction is also sent as expected.

To send custom variables to Contentsquare, define them before the Contentsquare main tag.

Modify the keys and values to your needs: you can get values from your Liquid Objects or Liquid Tags.

<script type="text/javascript">
// Contentsquare Send Custom Variables
window._uxa = window._uxa || [];
window._uxa.push(['setCustomVariable', 1, "Insert Custom Key 1", "Insert Custom Vale : " + {{ custom_tag.value1 }}]);
window._uxa.push(['setCustomVariable', 2, "Insert Custom Key 2", "Insert Custom Vale : " + {{ custom_tag.value2 }}]);
window._uxa.push(['setCustomVariable', 3, "Insert Custom Key 1", "Insert Custom Vale : " + {{ custom_tag.value3 }}]);
// Contentsquare Main Tracking Tag
(function () {
window._uxa = window._uxa || [];
if (typeof CS_CONF === 'undefined') {
window._uxa.push(['setPath', window.location.pathname+window.location.hash.replace('#','?__')]);
var mt = document.createElement('script'); mt.type = 'text/javascript'; mt.async = true;
mt.src = '//t.contentsquare.net/uxa/769238b6e1309.js';
document.getElementsByTagName('head')[0].appendChild(mt);
}
else {
window._uxa.push(['trackPageview', window.location.pathname+window.location.hash.replace('#','?__')]);
}
})();
</script>

For more information, see the setCustomVariable command.

You can send dynamic variables at any point in the pageview, they do not need to be set before the Contentsquare tag is loaded.

Modify the keys and values to your needs: you can get values from your Liquid Objects or Liquid Tags.

<script type="text/javascript">
// Contentsquare Send Artificial Pageviews
document.getElementById("AddToCart").addEventListener('click', function() {
window._uxa = window._uxa || [];
window._uxa.push(["setPath", "Added_to_cart_" + {{ custom_tag.value }}]);
window._uxa.push(["trackPageview"]);
window._uxa = window._uxa || [];
window._uxa.push(["trackDynamicVariable", {key: "Added to cart", value: {{ custom_tag.value }}}]);
});
</script>

For more information, see the trackDynamicVariable command.

To set up the Tag on your website, add the following lines of code on every page you want to analyze, either at the end of the <body> tag, or via a Tag Management System - YOUR_TAG_ID is the unique ID of your Contentsquare tag.

<script type="text/javascript">
(function () {
window._uxa = window._uxa || [];
if (typeof CS_CONF === 'undefined') {
window._uxa.push(['setPath', window.location.pathname + window.location.hash.replace('#', '?__')]);
var mt = document.createElement("script");
mt.type = "text/javascript";
mt.async = true;
mt.src = "//t.contentsquare.net/uxa/YOUR_TAG_ID.js";
document.getElementsByTagName("head")[0].appendChild(mt);
} else {
window._uxa.push(['trackPageview', window.location.pathname + window.location.hash.replace('#', '?__')]);
}
})();
</script>

This code creates a function which will add an asynchronous call to a script and then execute the function. This is a way to avoid other elements loading being blocked on the page. This reduces the impact of the tag on the website’s performance.

In order to collect custom variables from your datalayer, take a look at the following code example:

<script>
(function () {
window._uxa = window._uxa || [];
try {
if (typeof dataLayer !== 'undefined') {
for (var i = 0; i < dataLayer.length; i++) {
window._uxa.push(['setCustomVariable', 1, 'Sample Variable', dataLayer[i].sampleVariable, 3]);
}
}
} catch(e){}
if (typeof CS_CONF === 'undefined') {
window._uxa.push(['setPath', window.location.pathname+window.location.hash.replace('#','?__')]);
var mt = document.createElement('script'); mt.type = 'text/javascript'; mt.async = true;
mt.src = '//t.contentsquare.net/uxa/{{YOUR_TAG_ID}}.js';
document.getElementsByTagName('head')[0].appendChild(mt);
}
else {
window._uxa.push(['trackPageview', window.location.pathname+window.location.hash.replace('#','?__')]);
}
})();
</script>

Position the tag before the closing </body> marker within each page of your website.

To have the most reliable traffic count without slowing down the display of the page, load the script as soon as the page is displayed (DOMContentLoaded event).

Waiting for the whole page to load load event may impact the integrity of paths passed on as well as the amount of visits.

Do not forget to include all subdomains as well as the potential pages called by iFrames.

The tag contains:

  • A CS_CONF object gathering configuration elements of your own account, such as used domain, inclusion percentages, etc.
  • The latest Tag version.

Checking the loading of the main tag

Section titled Checking the loading of the main tag

Use the Contentsquare Tracking Setup Assistant Chrome Extension to confirm the main is loaded and that a first pageview is sent.

The tag is based on a window._uxa object which receives instructions from the push() function. It is thus possible to send instructions even before the library has finished loading by initializing the window._uxa variable via an array. We use the fact that arrays interpret the push() function natively.

This is why all instructions sent to the tag work the following way:

window._uxa = window._uxa || [];
window._uxa.push(<INSTRUCTION>);

The first line creates an array ([]) if the _uxa variable does not already exist. The second line adds an instruction to it.

If the library is already loaded, the instruction will be executed immediately. If it has not loaded yet, the instruction will be executed when the library has loaded. In both cases, this guarantees that the execution order of the commands will not generate an error.

You can call the main tag with CORS requests (Cross-origin resource sharing, more on this here). You just need to add crossorigin="anonymous" to the <script> tag of the main tag.

If there is a syntax error in the tag, an exception will be generated that can be caught by your site (with window.onerror for instance).

  • Without crossorigin="anonymous", you will catch a “Script error” message with no information on the initiator.
  • With crossorigin="anonymous", the message will log the file generating the error. You can use it if you watch errors on your website.

If you must self-host the tag, we advise you to set up automatic sync with http://t.contentsquare.net/uxa/{YOUR_TAG_ID}.js which always serves the latest version of the Tag.

Contentsquare does not serve specific pinned versions of the Tag to any public endpoints.

📬 Subscribe to the Tag Changelog to get notified of releases every month.