Get up and running with Chartbeat—full implementation guides for all our products.

Implement Chartbeat for Publishing

Introduction

Chartbeat is a real-time, JavaScript based, web analytics product. Our JavaScript, the chartbeat.js code, sends tracking pings from your users' browsers to our servers, and allows you to monitor traffic and engagement in real time. Installing chartbeat.js is as simple as adding one small snippet of JavaScript to your web page templates and modifying a few configuration variables.

The chartbeat.js code is set to deploy from a geographically distributed CDN (content distribution network) so as to efficiently serve the code to your users. Additionally, using the snippet below will set the code up to load without blocking other scripts from your site.

Our Code

Here’s our JavaScript.

We recommend inserting this script in your <head> tag.

If you’re setting canonical links, you must put the rel="canonical" link element before the Chartbeat script in the <head> tag.

If you are using HTML elements to set your section and author variables or your subscriber engagement, this script can be inserted in the <body> tag after these elements have been defined.

<script type='text/javascript'>
    (function() {
        /** CONFIGURATION START **/
        var _sf_async_config = window._sf_async_config = (window._sf_async_config || {});

        _sf_async_config.uid = #####; //CHANGE THIS
        _sf_async_config.domain = 'YourDomain.com'; //CHANGE THIS
        _sf_async_config.flickerControl = false;
        _sf_async_config.useCanonical = true;
        _sf_async_config.useCanonicalDomain = true;
        _sf_async_config.sections = ''; //CHANGE THIS TO YOUR SECTION NAME(s)
        _sf_async_config.authors = ''; //CHANGE THIS TO YOUR AUTHOR NAME(s)
        /** CONFIGURATION END **/
        function loadChartbeat() {
            var e = document.createElement('script');
            var n = document.getElementsByTagName('script')[0];
            e.type = 'text/javascript';
            e.async = true;
            e.src = '//static.chartbeat.com/js/chartbeat.js';
            n.parentNode.insertBefore(e, n);
        }
        loadChartbeat();
     })();
</script>

Important Notes:

Once this is implemented globally across your site, you might need to make a few configuration tweaks to better fit your site. All of these options are outlined in the rest of this guide.

The Chartbeat code above may also be deployed through a tag manager script.

For advanced implementation options see our Going Further Guide.

UID & Subdomains

By default the UID variable should be automatically set to your Chartbeat Account number when adding a new site. To retrieve the correct Chartbeat code for your account, head on over to chart.bt/setup. It will look like this:

_sf_async_config.uid = #####;

Tracking Subdomains

If your site employs subdomains, you have the option of tracking with Chartbeat in one of two ways:

  1. If you want to track a subdomain (e.g. "blog.yoursite.com") within an existing Dashboard, simply copy the exact same code that is on the existing domain and add it to the HTML of the subdomain.

  2. If you want to track a subdomain separate from your other Chartbeat Publishing Dashboards, select "add site" from the Chartbeat settings page, and follow on-site instructions.

Important Notes:

If you are adding a mobile subdomain, please refer to our Mobile Site Implementation for more information.

Canonical Links

Does your site use query parameters for various tracking purposes, (e.g. seeing people who came from an email newsletter)? Or does your site have multiple URL structures for the same page/article (e.g. domain.com/section/artcle vs domain.com/12345)?

By default, Chartbeat is configured to use either the raw path or canonical links (when available). We strongly encourage implementing canonical links to ensure consistent tracking of pages and to prevent seeing multiple listings of the same page in the Chartbeat Dashboard. If you're not familiar with canonical links, check out Google's Guide to Canonical Links.

To utilize the canonical feature, you'll need to ensure that your site defines canonical links for each page (e.g <link rel='canonical'.../>) and that the canonical variable is set to "true".

_sf_async_config.useCanonical = true;

Sections & Authors

In Chartbeat Publishing you can filter your content by section or author. To implement this feature, you’ll need to set up section and author variables within the Chartbeat code. So if a page is written by Bob Johnson in the section US Politics, you would set:

_sf_async_config.sections = "US Politics";
_sf_async_config.authors = "Bob Johnson";

A page can both be in multiple sections and/or have multiple authors, therefore each variable accepts a comma separated list of values. So if a page is co-written by Megan Summers and Kevin Smith in the sections Fashion and Fashion News, you would set:

_sf_async_config.sections = "Fashion,Fashion News";
_sf_async_config.authors = "Megan Summers,Kevin Smith";

The sections variable does not need to reflect real sections on the site, but should be thought of as groupings of pages that can be filtered on. Our suggestion is to populate these fields dynamically by tying them to a variable in your CMS which globally represents your sections and authors ​for the given page so they can be easily changed.

_sf_async_config.sections = cms.section.variable;
_sf_async_config.authors = cms.author.variable;

You can also populate these variables by using page metadata, a tag that already exists in your code, or part of your URL structure which contains these values.

Some examples on how to use these are below, but you know better than us how your site is structured.

If you have a .classname that you give to your authors, this would grab the value

Here's a link to MDN to learn more about it.
document.getElementsByClassName('authorContainer').innerText

If instead you give your authors an #ID, this would grab the value

Here's a link to MDN to learn more about it.
document.getElementById('authorContainer').innerHTML

Splits the URL to after the “.com” (good for Sections)

document.location.href.split('/')[3]

A broader way to select values from the DOM are below, which would work with meta data, sections and authors

Here's a link to MDN to learn more about it.

    document.querySelector('.byline').innerText

    document.querySelector('#news).innerText

    document.querySelector('meta[name="author"]').getAttribute("content")
    

If you populate your CMS variable with a data layer/tag manager (e.g. Google, Adobe, Tealium), you can call that object and iterate through to get your sections and authors


    dataLayer[0].gaSection

    digitalData.page.category.subCategory1

    digitalData.page.pageInfo.author
    

Custom Path Variable

If you are unable or prefer to not use canonical links, you may alternatively set the Path Variable. The path must start with "/" (forward slash) and we highly recommend that you use a real path used to navigate to this page.

The value set for the Path Variable should be generated by your CMS or set to window.location.pathname, so that the same piece of code can be used on all pages.

Examples of setting the Path Variable:

_sf_async_config.path = "/directory/path";
_sf_async_config.path = cms.path.variable;
_sf_async_config.path = window.location.pathname;

Important Notes:

If you are implementing Chartbeat on a separate mobile site (e.g. m.domain.com), please refer to our Mobile Site Implementation section.

Page paths which contain personally identifiable information (PII) should not be utilized in your Chartbeat implementation. If your page URLs contain PII and you need assistance removing this data from the page paths that are sent to Chartbeat, please email us at support@chartbeat.com

Custom Page Titles

By default Chartbeat displays page titles by using the <title> tag in your site's header.

You can override the title used for a page in Chartbeat by setting the Title Variable. This can be useful when all pages have a common prefix (e.g. "Publication Name: Story Title"), or when most pages share a common site title.

You can set the Title Variable manually, or populate it dynamically by tying it to a variable in your CMS.

Here you can set the title like this:

_sf_async_config.title = "Story Title";
_sf_async_config.title = cms.title.variable;

Mobile Site Implementation

If you have a separate mobile site (e.g. "m.site.com"), you’ll need to deploy Chartbeat code across all mobile pages. In order to track these pages within your existing Dashboard, just make sure to set the domain to the Desktop Domain name.

_sf_async_config.domain = 'site.com';

Canonical Links and Different Paths

Our best practice for combining mobile and desktop traffic for similar stories is to set the Path Variable on your mobile pages to the full canonical link of the desktop pages.

The line you will add to your mobile pages will look more or less like this:

_sf_async_config.path = '/matching-desktop-path';

Non-Canonical Links and Different Paths

To combine the mobile and desktop traffic for similar pages, you'll need to configure your Chartbeat implementation to identify the different versions as the same page.

The line you will add to your mobile pages should resemble:

_sf_async_config.path = 'site.com/matching-desktop-path';

Important Notes:

If you are interested in having a separate Chartbeat Dashboard for your mobile site, please have your account administrator add an additional site to your account. Once this is done, you can set the Domain Variable to point to the new Dashboard.

AJAX & Infinite Scroll

If your site uses infinite scroll, serves up content dynamically via AJAX, or pages change without the URL subsequently changing or the DOM refreshing, you’ll need to do some additional implementation.

Anytime a visitor navigates to a new page or piece of content, you’ll need to call the function virtualPage. This function is specifically designed to update our pinger information on this kind of page change, and can be attached to click/swipe events, or to a pixel that is used to trigger content changes. Best practice is to make sure that the virtualPage function is called whenever you change to a new page of content using AJAX, so they always happen together.

You’ll need to setup logic to handle these lines of code:

pSUPERFLY.virtualPage({
      sections: "New Section 1, New Section 2",
      authors: "New Author",
      path: "/newpath",
      title: "New Title"
    }):

If we are not passed the updated section and author information we’ll continue to register the original sections and authors from the previous page. If the new page has no section or author data, simply set that variable to "null". For example:

authors:"",

When the page changes we’ll need to populate the path and title for the new page(s) within the virtualPage variable, so that the pings will reflect the new page the visitor is on.

Important Notes:

virtualPage should never be called when a user initially arrives on a page from an external source, and should only be called when a user navigates to subsequent pages without causing the DOM to be refreshed.

For pages with infinite scroll, any time a visitor is scrolling down to a new page, they will ping on each distinct URL they hit at least once.

Subscriber Engagement

If you allow users to login to your site, or provide subscriber-only content, pass this information to Chartbeat in order to see how much time different types of users spend engaging with your content. First, you'll need to declare a global _cbq variable with the following code:

var _cbq = window._cbq = (window._cbq || []);

Then, based on what type of user is currently browsing your site, we want to push the following array elements that constitute a key:value pair to the _cbq array:

_cbq.push(['_acct', 'user_type']);

Always push '_acct' as the first element in the array, with that representing the key of a key:value pair. The second element in the array represents the value of the key:value pair. For the user_type value, please use one of the three standardized values below:

Subscriber Value user_type
Guest: 'anon'
Registered: 'lgdin'
Subscriber: 'paid'

Generally, it's best practice to declare _cbq and perform your _cbq.push() right after your _sf_async_config setup. For example, if you wanted to push a user type of 'paid' your implementation might look like:

<script type='text/javascript'>
    (function() {
        var _sf_async_config = window._sf_async_config = (window._sf_async_config || {});
        /** CONFIGURATION START **/
        _sf_async_config.uid = #####; //CHANGE THIS
        _sf_async_config.domain = 'YourDomain.com'; //CHANGE THIS
        _sf_async_config.useCanonical = true;
        _sf_async_config.useCanonicalDomain = true;
        _sf_async_config.sections = ''; //CHANGE THIS TO YOUR SECTION NAME(s)
        _sf_async_config.authors = ''; //CHANGE THIS TO YOUR AUTHOR NAME(s)
        var _cbq = window._cbq = (window._cbq || []);
        _cbq.push(['_acct', 'paid']);
        /** CONFIGURATION END **/

        function loadChartbeat() {
            var e = document.createElement('script');
            var n = document.getElementsByTagName('script')[0];
            e.type = 'text/javascript';
            e.async = true;
            e.src = '//static.chartbeat.com/js/chartbeat.js';
            n.parentNode.insertBefore(e, n);
        }
        loadChartbeat();
     })();
</script>

Cookies

Chartbeat uses three first-party cookies.

  1. The _chartbeat2 cookie is used to register if a user has visited the domain before and to calculate visitor frequency.
  2. The _chartbeat4 cookie stores the state of the last ping when a page is unloaded and is used for accurately calculating engaged time.
  3. The _chartbeat5 cookie is used by the Heads Up Display to assign traffic to the right link on the page from which someone clicked over.

Disabling Cookies:

Customers who are subject to the EU e-Privacy Directive, or who would prefer not to use cookies, can set the following variable to prevent Chartbeat from using cookies.

_sf_async_config.noCookies = true;

Note: By using Chartbeat without cookies, you will be unable to see Visitor Frequency, Conversion Quality, and Return Rates.

Here are some ways to get in touch.