The data privacy landscape is constantly changing, and to add further complexity for developers, every company has its own security needs and requirements. Pardot’s new Tracking & Consent JavaScript API gives developers greater flexibility and control over how and when user tracking takes place. In this post, we’ll introduce you to the new API, and we’ll show you how to use it for your cookie consent requirements and how to embed it within single-page applications (SPAs).

How to set up the Tracking & Consent JavaScript API

The first step is to opt in to using the API from the Account page in Pardot. If you do not do this step, no page view is recorded and no response is given to honor the privacy of the users interacting with your content. You can do so by clicking the Edit button on the Account page and checking “Activate the Tracking & Consent JavaScript API.” For more information on Account settings, please refer to the Pardot documentation.

In order to leverage our new API on your sites, you’ll have to generate the tracking code in your Pardot setup.

Next, you’ll copy and paste this script into your web page HTML before the close body tag (</body>) and make a few changes to opt into the API. Let’s take a closer look at what those changes look like.

How the Tracking & Consent JavaScript API works

The following code block shows what changes need to be made to the generated tracking script in order to leverage the new API. There are three key elements:

  • In line 13, we generate a global JavaScript object that is attached to the window object. This is called the “tracker object” and will be used to interact with the API.
  • It is mandatory to initialize the tracker object using the create command before any tracking can occur, as shown in line 18.
  • After you’ve initialized the object, you can push subsequent commands, such as the sendPageView command in line 21, to the tracker object. Those commands are added to the tracker object’s queue and executed synchronously.
<script>
    piAId = 123456;
    piCId = 654321;
    // Optional Account Pardot Tracker Domain hostname, will
    // fallback to pi.pardot.com if not provided
    piDomain = 'go.example.com'; 

    (function() {
         // The src value will now load pdt.js instead of pd.js
        var s=document.createElement('script');s.type='text/javascript';s.async=true;s.src='//'+piDomain+'/pdt.js?aid='+piAId;
        var c=document.getElementsByTagName('script')[0];c.parentNode.insertBefore(s,c);
        // Initialize the queue
        window['pdt'] = window['pdt'] || function(){(window['pdt'].cq = window['pdt'].cq || []).push(arguments);};
    })();
    
    // Creating an analytics tracker requires the following:
    // pdt('create', <pardot account id + 1000>, <pardot campaign id + 1000>, 'go.example.com');
    pdt('create', piAId, piCId, piDomain);
    
    // Push commands onto the queue
    pdt('sendPageView');
</script>

If you’re already familiar with our previous tracking mechanism, you may immediately notice that the variables piAId and piCId are now integer values. Those variables, which represent your account and your campaign IDs, were previously string values.

Once the tracker object is created, there is a wide range of commands that you can push onto the queue, including (but not limited to): updating the value of a tracked field, setting a user’s opt-in status, displaying the opt-in banner, and sending an analytics request back to Pardot. It is also possible to interact with the tracker object and the associated commands outside of the tracking snippet. All you need to do is call back to the Pardot API from inline JS or another JS file. You can find the list of commands and correct syntax in the Tracking and Consent API Overview.

How to implement cookie consent banner handling

Cookie consent laws and regulations can vary depending on your region. Our API can help ensure that you are always compliant and respecting the privacy of those interacting with your content. We hydrate the consent banner with HTML from your account’s tracking opt-in preferences, which gives you the power to display the banner when necessary.

To acquire your users’ initial consent, you can add the showConsentBanner command to your tracking snippet after creating the tracker object.

<script>
   /*
    * Beginning of tracking snippet
   */

    pdt('create', piAId, piCId, piDomain);
    pdt('showConsentBanner');
</script>

A call to showConsentBanner from the Tracking & Consent JavaScript API will resurface the consent banner, enabling website visitors to make changes to their consent preferences. This can be done in the form of buttons or links on your website that users can use to re-open the banner.

<button type="button" id="show_banner_button" onClick="pdt(\'showConsentBanner\')">
    Cookie Consent Settings
</button>

hideConsentBanner is another command within the API that allows you to handle consent changes. When you pass in a Boolean value, it will set the optIn status — just as it does when you click “Yes” or “No” on the banner. It will also hide any HTML that exists under your consent banner ID.

<button type="button" id="hide_banner_button" onClick="pdt(\'hideConsentBanner\', null)">
    Hide Cookie Consent Settings
</button>

Check out the Tracking and Consent API Overview to learn more about the different consent commands and their parameters.

How to implement the API for single-page applications

Our legacy, first-party tracking code is executed only during page load or when the user submits something to the server. This made it incompatible with SPAs as they don’t require full page loads. With our new API, we filled this gap to allow you to use Pardot tracking in every kind of web application.

SPAs can vary based on the framework that you’re using. The following code snippet shows a generic implementation that tracks when a user navigates on our SPA to a different page.

  • Starting on line 1, we embed the updated tracking snippet
  • Lines 18 and 19 hold anchor tags for the navigation elements
  • Starting in line 23, we implemented an immediately invoked function (also knows as IIFE), which does two things:
    • It creates a local function, trackView, which will be used to send commands to the tracker object.
    • It queries the navigation elements on our page and attaches a onclick listener to each element. The onclick event will then trigger the invocation of the trackView function.
<!-- Embed the Pardot analytics library -->
<script type='text/javascript'>
var piDomain = 'go.example.com';

(function(){
    var s=document.createElement('script');s.type='text/javascript';s.async=true;s.src='//'+piDomain+'/pdt.js';
    var c=document.getElementsByTagName('script')[0];c.parentNode.insertBefore(s,c);
    window['pdt'] = window['pdt'] || function(){(window['pdt'].cq = window['pdt'].cq || []).push(arguments);};
})();

// Creating an analytics tracker requires the following:
// pdt('create', <pardot account id + 1000>, <pardot campaign id + 1000>, 'go.example.com');
pdt('create', 0001, 0002, piDomain);
</script>
<!-- End embed Pardot analytics -->

<!-- example menu navigation -->
<a href="/home">Home</a>
<a href="/about">About</a>
<!-- end example menu navigation -->

<script>
(function() {
   // Update the tracked page title and send a page view to Pardot
   function trackView(pageTitle) {
        pdt('set', 'title', pageTitle);
        pdt('sendPageView');
   }
   
   // Add event listeners for clicks on navigation links
   // Clicks on these links will send page views to Pardot
   let navLinks = document.getElementsByClassName('navigation-link');
   for (let i = 0; i < navLinks.length; i++) {
        navLinks[i].addEventListener('click', trackView(navLinks[i].text), false);
   }
})();   
</script>

Summary

The Tracking & Consent Javascript API is now available for you to use! While cookie consent and single-page applications are two important examples of how to use the API, it can also be utilized for a wide range of use cases. For more information on the Tracking & Consent Javascript API, check out the official Tracking and Consent API Overview and the Spring ’22 release notes.

About the author


Katherine Pellman is a Software Engineer for Pardot. She joined Salesforce in August 2021 after graduating from the University of Texas with a degree in Computer Science.

Get the latest Salesforce Developer blog posts and podcast episodes via Slack or RSS.

Add to Slack Subscribe to RSS