Facebook Pixel & Analytics for Media Publishers: Integration Guide

Facebook Analytics allows you to understand and optimize your audience journey with rich demographics based on the events you log with Facebook Pixel on your website. This guide will help you implement Facebook Pixel on your website in order to measure the event data on Facebook Analytics and demonstrate the practical logging methods for media publishers.

Getting Started

To create a Facebook Pixel, you'll need to make sure that you have an ad account. Once your ad account is set up, you can get a pixel code on Ads Manager to set up on your site. The basic example code looks like this:

<script type="text/javascript">
!function (f, b, e, v, n, t, s) {
    if (f.fbq) return; n = f.fbq = function () {
        n.callMethod ?
            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
    }; if (!f._fbq) f._fbq = n;
    n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
    t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
}(window,document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');

fbq('init', '{pixel-id}');
fbq('track', 'PageView');
</script>

You can confirm your Pixel is firing events by using Ads Manager or Facebook Pixel Helper. You can also do this with Facebook Analytics Event Debugging: https://www.facebook.com/analytics/{pixel-id}/?section=most_recent

A few hours after you implement Facebook Pixel, you're able to view active user data, demographics on your audience and more in your Facebook Analytics dashboard at https://www.facebook.com/analytics/{pixel-id}/

You can segment your audiences by common web parameters, such as URL, referrer, traffic source and UTM parameters.

Facebook Analytics can be accessed by anyone with a role in the ad account that the Pixel belongs to. So be sure to add people to roles for your ad account if you share the Analytics dashboard with them.

The Facebook Pixel uses JavaScript to send HTTPS requests to a Facebook URL like https://www.facebook.com/tr/?id={pixel-id}&ev={event-name}&... along with cookies. Facebook Analytics recognizes users through these cookies. So if a user clears their browser cookies, they are counted as a new user.

If a Facebook user uses two or more browsers (such as mobile and desktop), Facebook Analytics recognizes the user as a single user, not two distinct users. This is possible because the Facebook cookies used on each browser are linked to the same logged-in Facebook user.

Standard Events and Custom Events

By default, Facebook Analytics supports a number of common web parameters such as domain, URL, referrer, and utm_* query. Facebook Pixel automatically collects these parameter values. Publishers can add their own parameters and and event names to customize the tool to their needs.

9 standard events are defined in the Pixel Code Reference API:

  • ViewContent
  • Search
  • AddToCart
  • AddToWishList
  • InitiateCheckout
  • AddPaymentInfo
  • Purchase
  • Lead
  • CompleteRegistration.

To log one of these, you have to use track as the first parameter:

fbq('track', {'STANDARD_EVENT_NAME'}, {EventParams});

You can add your own custom events, changing the first parameter to trackCustom:

fbq('trackCustom', {'CUSTOM_EVENT_NAME'}, {EventParams});

Logging Examples

This section describes more common use cases and best practices to measure media publisher–specific data using the Facebook Pixel.

Log Article Views

The standard PageView event should be used to log article views associated with loading a URL:

// Log URL access
fbq('track', 'PageView');

A PageView event may not necessarily equate to content access, i.e if you load in additional content into the page. Therefore, you can also use the ViewContent event to log explicitly whether someone has viewed some content e.g. watched a video:

// Log content views 
fbq('track', 'ViewContent', {
   id: 'article-1234',
   title: 'Awesome Article',
   author: 'joedoe',
   published_at: '2017-09-01 12:00',
   categories: ['economy', 'united-states'],
   // ...additional parameters to track
});

After deploying this logging code, you can see ViewContent and the following parameters on the Facebook Analytics event debugger: id, title, author, published_at, and categories.

The ViewContent event is a standard event and Facebook Analytics shows it as Content View.

Log Query Parameters

The Facebook Pixel logs the current URL (window.location.href value), but Facebook Analytics only handles utm parameters (utm_source, utm_medium, etc) and doesn't handle other custom query parameters. If you want to log your custom query parameters on Facebook Analytics, you need to add these query parameters as event parameters. Please note the number of event parameters per an event must be less than 25.

function parseQuery(){
  var keys = Array.prototype.slice.call(arguments);
  var sep = '&';
  var eq = '=';
  var text = window.location.search.substr(1);
  return text.split(sep).reduce(function(obj, v) {
    var pair = v.split(eq);
    if( keys.indexOf(pair[0]) >= 0 ){
      obj['query-' + pair[0]] = decodeURIComponent(pair[1]);
    }
    return obj;
  }, {});
}

var queryParams = parseQuery('p');
fbq('track', 'PageView', queryParams);
fbq('track', 'ViewContent', Object.assign({
   id: 'article-1234',
   title: 'Awesome Article',
   author: 'joedoe',
   published_at: '2017-09-01 12:00',
   categories: ['economy', 'united-states'],
}, queryParams));

For the example above, an event parameter, query-p, is logged along with other article attributes if someone views http://{your-website}/article/{id}?p=1. You can use this parameter name for the segment condition with other web parameters, like URL. This is helpful if your articles are divided into several pages and the p parameter specifies the location in an article. For example, you can easily filter audiences who reached the p=2 location in your article.

Or you can create an article read funnel by using a combination of the Segments and the Funnel features. The following Segment configuration shows a funnel from p=1 to p=2 for audiences who viewed an article (article-1234), which says 31.5% of people viewed the content at p=2 after viewing the content at p=1.

User Segment

Funnel

If you select the [SHOW BY] drop down at the right side in the funnel view, you can see more detailed demographics data for this funnel.

ViewContent is a standard event and Facebook Analytics shows it as Content View

Log Article Views on Instant Articles

The Facebook Pixel logging code can be used on Instant Articles within the op-tracker tag. So you can log PageView and ViewContent events within the op-tracker tag. One of the important things to note is that the window.location.href value is always the canonical URL associated to the Instant Article.

<figure class="op-tracker">
  <iframe>
    <script>
    (function (f, b, e, v, n, t, s) {
        if (f.fbq) return; n = f.fbq = function () {
            n.callMethod ?
                n.callMethod.apply(n, arguments) : n.queue.push(arguments)
        }; if (!f._fbq) f._fbq = n;
        n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
        t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
    }(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js'));

    fbq('init', '{pixel-id}');
    fbq('track', 'PageView');
    fbq('track', 'ViewContent', {
       id: 'article-1234',
       title: ia_document.title,
       author: 'joedoe',
       published_at: '2017-09-01 12:00',
       categories: ['economy', 'united-states'],
       platform: 'InstantArticles',
    });   
    </script>
  </iframe>
</figure>

If you want to log query parameters used for posts, you need to use ia_document.shareURL to parse these parameters.

Log Scroll Depth

The example above uses a query parameter to log the depth of content views. If you have a single page article, you can log scroll depth by using JavaScript view port events. fbq() can be called anywhere in your JavaScript code, so the logging code would be like this:

function getCurrentPosition() {
    return window.pageYOffset ||
        (document.documentElement || document.body.parentNode || document.body).scrollTop;
}

function getScrollableHeight() {
    var d = Math.max(
        document.body.scrollHeight, document.documentElement.scrollHeight,
        document.body.offsetHeight, document.documentElement.offsetHeight,
        document.body.clientHeight, document.documentElement.clientHeight
    )
    var w = window.innerHeight ||
        (document.documentElement || document.body).clientHeight;
    if (d > w) {
        return d - w;
    }
    return 0; // not scrollable
}

var checkPoints = [10, 30, 50, 70, 90];
var reached = 0;
var scrollableHeight = getScrollableHeight();

window.addEventListener('resize', function () {
    scrollableHeight = getScrollableHeight();
});
window.addEventListener('scroll', function () {
    var current;
    if (scrollableHeight == 0) {
        current = 100;
    } else {
        var current = getCurrentPosition() / scrollableHeight * 100;
    }
    if (current > reached) {
        reached = current;
        // checkpoint and send events
        while (checkPoints.length > 0) {
            var c = checkPoints[0];
            if (c <= reached) {
                checkPoints.shift();
                fbq('trackCustom', 'ViewContentCheckPoint', {
                    depth: c,
                });
            } else {
                break;
            }
        }
    }
}, false);  

The example above checks the scroll depths on the browser and fires the ViewContentCheckpoint custom event if it exceeds checkpoint values, 10%, 30%, 50%, and 90%. This enables you to analyze the data by scroll depth percentage.

Log Views of ADs in An Article

Similar to scroll depth logging, it can be valuable to log how people view the specific parts of your articles. For instance, if you put ads in your article, you may wish to log ad view events.

Let's say the article HTML code is as below:

<div>
...Content...
</div>
<div class="native-ad-block">...</div>
<div>
...Content...
</div>
<div>
...Content...
</div>
<div class="native-ad-block">...</div>
...

So views of DOM elements specified by 'native-ad-block' can be logged as follows:

function isInView(element) {
    var rect = element.getBoundingClientRect();
    var h = (window.innerHeight || document.documentElement.clientHeight);
    var w = (window.innerWidth || document.documentElement.clientWidth);
    return (
        rect.top >= 0 && rect.left >= 0 &&
        rect.bottom <= h && rect.right <= w
    );
}

var elements = document.getElementsByClassName("native-ad-block");
var viewed = new Array(elements.length);
window.addEventListener('scroll', function () {
    for (var i = 0; i < elements.length; i++) {
        if (!viewed[i] && isInView(elements[i])) {
            viewed[i] = true;
            fbq('trackCustom', "ViewAdBlock", {
                index: i,
            })        
        }
    }
});

The logging code above enables you to see which audiences are actually viewing your ads. Log entries are triggered by ViewAdBlock events.

Log Link Clicks

It's also possible to log actions taken on your site as well, such as content consumption. Again, fbq() can be called anywhere in your script, allowing you to log clicks on your page and see the demographics for theses audiences. Please note that most browsers stop executing JavaScript once a new page starts to load. fbq() calls HTTP requests asynchronously and doesn't support callbacks, so setting a timeout to start to load a new page is the only way to safely log link clicks.

function setLogAndClick(elm) {
    var logged = false;
    elm.onclick = function (e) {
        if (logged) {
            return;
        }
        e.preventDefault();
        // wait 500ms and re-execute click event;
        setTimeout(function () {
            elm.click();
        }, 500);
        fbq('trackCustom', 'LinkClick', {
            href: elm.href
        })
        logged = true;
        return;
    }
}

var loggings = document.getElementsByClassName('loggings');
for (var i = 0; i < loggings.length; i++) {
    setLogAndClick(loggings[i]);
}

Log Social Plugin Events

If your website integrates the Facebook SDK and uses social plugins, you may wish to log these plugin events with the Facebook Pixel so that you can see who posts comments on articles. These plugins have an API to subscribe events FB.Events.subscribe so logging code will be implemented as follows:

(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.10&appId={your-app-id}";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

window.fbAsyncInit = function () {
    FB.Event.subscribe('comment.create', function (comment) {
        fbq('trackCustom', 'SocialPluginComment');
    });
}