How to detect mobile device on Google Tag Manager, DTM & Tealium

Wwwhhhooaaaa this form looks perfect AF! Lemme check how it looks on mobile ???

Mobile responsiveness is a task, isn’t it? The most beautiful features on desktop, might sometimes appear disastrous on a mobile device. If a similar situation is ruining the mobile experience of your website, and you’re looking for a way to show certain features only to your desktop audience or vice versa, here’s how you can do it.

I’ll be helping you detect the device type of your visitors and use that data to serve different (and pleasant) experience on different devices (desktop and mobile).

Following is a detailed procedure on how you can achieve it using Google Tag Manager, but we will also talk about how you can do it on Dynamic Tag Manager by Adobe, and Tealium. Let’s get started!

Detecting a Mobile Device on Google Tag Manager

We’re going to divide the job into three parts.

I – Variable creation
II – Trigger creation
III – Application

I – Creating a variable

We’re creating a variable which returns the value true for a mobile device, and false otherwise. This variable is our device detector!

1 – On your GTM dashboard, go to Variables and click on New.

2 – Give a relevant name to your variable, and under the Variable Configuration, choose Custom JavaScript. I’ve named my variable as Device Check.

3 – Thanks to http://detectmobilebrowsers.com, which is an open source for mobile detection scripts in various programming languages, we can get a JavaScript snippet for our variable. Choose JavaScript and save the .txt file. Then just copy the entire code from the file and paste it as the custom JavaScript of your variable.

Alternatively, you can also just copy the script from here.

function () {
 var a = navigator.userAgent || navigator.vendor || window.opera;
 if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) { return true; }
 return false;
 }

Paste the above code as the custom JavaScript of your variable and click Save. Our variable has been created!

II – Creating a Trigger

Now that we’ve detected the device type, this triggers our next action : Decide what our visitor gets to see! Based on the value returned by our variable, i.e., true for mobile and false for desktop, we’ll create a trigger.

1 – On your Google Tag Manager dashboard, go to Triggers and click New.

2 – Name your trigger and under Trigger Configuration, choose Custom Event.

3 – Since we want this trigger to fire at every page hit, under Event Name, type .* and check the checkbox to enable Use Regex Matching.

4 – Now is when our variable and trigger come together. From the two radio buttons, choose Some Custom, and apply condition to include or exclude a mobile device. To exclude a mobile device, we want to go ahead with devices that return false to our variable. This is what our condition must look like –

The above condition excludes mobile devices. If you want to exclude desktops/tablets, you can put the value true in the last field.

So now, we’re ready to finally achieve our goal of excluding/including mobile devices!

III – Application

The whole idea behind this article came from our own experience with a pop-up form that worked just fine on my laptop, but fucked up on mobile devices. We wanted to hide the form from our mobile audience, solved it and thought you might need the solution some time! And so the example application here, is a Mailchimp subscriber pop-up form that we added to our website by creating a tag on Google Tag Manager. Here’s the tag without any trigger exceptions –

We edited the Triggering settings of our Mailchimp tag, and of course employed the trigger we created in Step II. To add a trigger to your tag, click the Triggering tab and choose the trigger you created earlier for the task (Step II). That’s all!

DIY – Test our form on your desktop and mobile device! Open datavinci.com on private window of your browser.

So that’s how you can use Google Tag Manger to detect device types. Let’s see how you can achieve it on DTM (Adobe’s Dynamic Tag Manager)

Detecting a Mobile Device on Dynamic Tag Manager or Adobe Launch

On DTM or Launch, the process is much simpler. While creating any kind of rule, you get an inbuilt condition to select the device type. Just select the device for which you want to fire the tag from the drop down, as shown in the screenshot below :

DTM mobile device rule

You see? It’s that simple!

Detecting a Mobile Device on Tealium

In Tealium, it is not as straight forward as Adobe, but it’s still pretty simple. Following are the steps:

1 : Adding data source
Create 2 Data Layer elements:
  • device_mobile
  • device_tablet

(You can name them whatever you feel suits your business logic)

Step 2: Fill up your data layer values using a javascript extension

 

  • Select the add extension option -> Go to the ‘Advanced’ tab > Select ‘JavaScript Code’
  • Name your extension and paste the following code in the configuration field.
    // global var to detect mobile devices based on user agent
    utag_data.device_mobile = ((function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))return true})(navigator.userAgent||navigator.vendor||window.opera))?'true':'false';
    
    // global var to detect tablets based on user agent
    utag_data.device_tablet = ((function(a){if(/ipad|android.+\d safari|tablet/i.test(a))return true})(navigator.userAgent||navigator.vendor||window.opera))?'true':'false';
  • !!! IMPORTANT: Set the scope to ‘Pre Loader’ !!!

Step 3: Create your load rules

Detect Mobile device in Tealium Step 3
Build your load rules:
  • is Mobile true: device_mobile / equals / true (if you want to trigger things on mobile devices)
  • is Mobile false: device_mobile / equals / false (if you do NOT want to trigger things on mobile devices)
  • is Tablet true: device_tablet / equals / true (if you want to trigger things on tablet devices)
  • is Tablet false: device_tablet / equals / false (if you do NOT want to trigger things on tablet devices)

Step 4: Use your load rules / Save / Test / Publish / Have a drink (This is important)

How we can help

So that’s how you can take control of what your visitors see, depending on their device type. And there’s so much you can do with it! I hope this article was helpful. Feel free to reach out to us for any queries that you might have. Also, if you don’t have time to learn and apply the magic of analytics, that’s what we are here for! We are a crazy team of Google and Adobe Certified Analytics Experts who eat, breathe, sleep and dream Analytics. And we’ve made it our purpose and passion to electrify your business’s potential through Analytics.

Contact us here.

Found it informative? Leave a comment! You can also give us a thumbs up by sharing it with your community. Also did you know that you can light up our day by subscribing to our blog? Subscribe here –


Implementing Facebook Pixel via Google Tag Manager

*seo stuff – Implementing Facebook Pixel via Google Tag Manager * 😀

The Importance of Facebook Pixel

Imagine this offline scenario – You own an apparel store which sells clothing for men and women. Every day, you meet and greet your customers and you even know some of them well. But one morning, instead of your regular human visitors, some black figures visit your store to shop. And now that happens everyday, all day long. No human customers anymore. Just those black figures, which you can’t even distinguish in terms of appearance, gender, age, or any physical feature, because they are all alike, all black.  Lol wtf right?

All of them are having fun at your store, loving your products, trying stuff, shopping and then leaving. At any day, you won’t even know if they are new ones or if they had visited earlier.

How then, would you know the characteristics of your customers? How would you know if more number of women are shopping, or more men? Or if most of your customers are young or middle aged?

Maybe you would know which of your products sell the most, but you would have no clue about who is buying them. You would have no clue about the type of audience that you must target in order to get more sales. Can you imagine?

Okay don’t cringe. That’s not gonna happen if you own a brick-and-mortar store. But do you own a website? If yes, there’s no way you can ‘see’ your customers while they’re exploring or shopping at your online store. It’s just like knowing that a black figure has entered your website. And it’s only legit if this thought makes you cringe. But since I’m writing about Facebook Pixel, it surely is the superhero-coming-to-the-rescue here. It gives you digital eyes, just like RedBull gives you wings. And that’s just one of the many things it does for you.

Sure we have Google Analytics and other analytics tools which collect information about visitors and you can do a doubleclick cookie integration in your GA account, but dude! Facebook knows EVERYTHING about everyone. This Mr-know-it-all knows your cousin’s wedding anniversary, and your mother’s birthday.

And in order to put this information to use, Facebook created Facebook Pixel. Facebook Pixel is a small code that we place on our website, and its function is to collect data for a myriad of goals that we can accomplish later.

The most important thing a pixel does is, umm, everything it does seems important! But okay, I’d like to describe two of the most important ones. One, it can be used for Remarketing on Facebook. You must have noticed that Facebook shows you adverts about stuff that you already have been looking for. For example, if you recently explored some online stores for track pants, be sure to see some relevant suggestions on Facebook! That’s remarketing. Facebook records your browsing activity and shows you ads based on your interests. This is accomplished by advertisers with the help of Facebook Pixel.

And remarketing has statistically been proven to improve conversion rates. Moreover, you can also use this base of past visitor to promote to them new stuff as well. This will greatly help you in refining your campaigns for optimum returns on your marketing spends.

Two, it allows you to build a lookalike audience of people who have similar interests and demographics to people who are already showing interest in your website. This means that you can target people who are similar to your current customers. It’s a great way to not only reach new people, but new potential customers.

Facebook Pixel also helps to track conversions and run effective ads. Again, so important!

Having made it clear that you must install a Facebook pixel to your website right away, let’s see how you can do it.

*seo stuff – Implementing Facebook Pixel via Google Tag Manager * 😀

Implementing Facebook Pixel via Google Tag Manager

To install a Facebook Pixel into your website through Google Tag Manager, you need access to a Facebook Business Manager account and a Google Tag Manager account. The following steps will take you through the installation process.

  • Log into your Facebook account and switch to Business Manager.
  • Open the Business Manager Menu and click on Pixels.

  • Give a name to your pixel and create it.

  • Having created the pixel successfully, you  now need to install it to your website, for which we’re using Google Tag Manager here.
  • Click on Setup and you will now be able to see a pop-up like this. Choose the first option.

  • Select Google Tag Manager from the list of tools.

  • Another pop-up will present you with the following options.

  • You can go with either of them, depending upon your convenience. If you would like to install the code manually, you’d have to copy it, create a Custom HTML tag in your Google Tag Manager Dashboard, and then paste the code under the tag’s HTML. If you go with the Quick Install, a tag gets automatically created in your GTM account.
  • Choosing Quick Install presents you with further steps which are quick, easy and smooth. Finally, publish.

  • Now log into your Google Tag Manager account to verify that the tag has been created. You’ll be able to see a Base Pixel Code tag under the Tags tab.

That’s all! The pixel starts working in a few minutes. You can now start receiving insights and tracking the performance of your website, right at your Facebook Business Manager account.

*seo stuff – Implementing Facebook Pixel via Google Tag Manager * 😀

Other Benefits

With GTM, you can not only implement this pixel but also “conveniently” pass custom data into facebook. Data like which products are users viewing, at which depth they are exiting the checkout, are they submitting any forms? etc etc

All this custom information will help you in further refining the definition of your target segment. With a refined audience segment you can expect optimum returns per penny spent. At the end of the day, its all about increasing the profits and reducing the costs and such consistent incremental optimizations can give you a huge advantage in your market.

Let me know your thoughts in the comments below.

*seo stuff – Implementing Facebook Pixel via Google Tag Manager * 😀

How we can help

Without any technical intricacies, you can install a Facebook Pixel and start collecting valuable visitor data on Facebook as well as Google Tag Manager. The next step would be to make the most out of your pixel, by deploying it for the very effective marketing techniques like Remarketing, lookalike audience and conversion tracking. And that’s what we are here for. We are a crazy team of Google and Adobe Certified Analytics Experts who eat, breathe, sleep and dream Analytics. And we’ve made it our purpose and passion to electrify your business’s potential through Analytics.

Contact us here.

Found it informative? Leave a comment! You can also give us a thumbs up by sharing it with your community. Also did you know that you can light up our day by subscribing to our blog? Subscribe here –


*seo stuff – Implementing Facebook Pixel via Google Tag Manager * 😀

Analytics with React-Redux SPAs and Google Tag Manager

React-Redux has become a hugely popular web development combo, but there aren’t too many guides out there on how to sprinkle in analytics. Most implementations require some modification to your app’s code, often with analytics specific business logic.

The most common pattern seems to be with redux middleware, which definitely is a step in the right direction. The redux-analytics package encompasses this pattern nicely. Every redux action becomes a place where insights can be extracted, simply by appending some analytics information to the action metadata.

const action = {
  type: 'MY_ACTION',
  meta: {
    analytics: {
      type: 'my-analytics-event',
      payload: {
        some: 'data',
        more: 'stuff'
      }
    }
  }
};

This is a great start, and I had many of these analytics payloads throughout the codebase for a while and it worked great. The problem was that whenever someone wanted to change pretty much anything, it required a redeployment. Plus you’ll often have less tech savvy users wanting to add their own insights.

We already had an integration with Google Tag Manager (gtm.js), so I was a little biased towards this implementation. This goes two-fold for other departments who were already familiar with gtm.js, which is currently reaping it’s benefits with less development overhead when adding analytics insights.

Anyway lets get started on a basic Redux integration with gtm.js and my personal analytics platform of choice — Mixpanel.


Getting Started

If you’re not already familiar with gtm.js, you can simply inject it’s javascript snippet into your app then get going. All of the configuration is driven through the gtm web UI, which has come a long way in the years.

Now on the app side, the Redux middleware approach is still the way to go here:

const analytics = () => next => action => {
  window.dataLayer = window.dataLayer || [];
  dataLayer.push({
    event: action.type,
    payload: action.payload
  });
  return next(action);
};
// Add in the analytics middleware
let store = createStore(
  todoApp,
  applyMiddleware(
    analytics,
    thunk,
  )
);

Instead of dispatching analytics events from the application, it’s now firing everything to the gtm.js dataLayer. Each dataLayer event needs an event attribute to denote the type of event, but other than that you can structure your data format in any way that suits your application.

Now that’s pretty much it for the initial setup, assuming you already have the gtm.js snippet embedded in your application somewhere. Everything else can now be driven by the Tag Manager UI. I’ve started storing tags/triggers/variables in their own respective folders, but these can be changed at any time.


Creating the first event

To get started, lets setup the beloved page load events that management always seems to want. A typical React SPA usually has some form of client-side routing, so there needs to be a method to track the initial page view (landing) and route transitions. To capture both of these, 2 triggers are required.

Create the trigger in some folder of your choice

First, create the tag for the page load. I used the window loaded trigger here, and named it Global.pageLoad for use later.

Create the first pageLoad event

Next, create the history change event, which will capture route transitions from your SPA router (e.g. react-router). This is similar to the Window Loadedevent above, but the History Change trigger can be selected instead.

Create a new tag Page View that triggers on either of these. I’ll be using Mixpanel throughout, but the same can apply to Google Analytics or your platform of choice.


Tracking authentication

The place where Mixpanel shines is tracking arbitrary events, with arbitrary (and sometimes changing) event attributes. This is the perfect behavior for a dynamic web application, and especially for the range of redux events that are fired.

In many applications, there’ll be some kind of authentication event fired. In my current app it’s structured as follows:

const authenticateAction = {
  type: 'AUTHENTICATE',
  payload: {
    user,
    token
  }
}

1. Create the trigger

This event is now available to use in Tag Manager as a custom event. Create a new trigger referencing this authenticate action:

The Event name should match the string type field in the redux action

2. Access the data

To access variables within your redux events, you need to create a Tag Manager variable for each primitive you want to access. Unfortunately there is no object dot notation access (yet).

Access the user id variable within the redux action

3. Send the analytics event

The complete authentication tag

Now that we have the trigger, and the data, we can send an analytics event. For user identity, this often varies per analytics-platform.

Create a new tag that uses the previous AUTHENTICATE event, along with the User.id variable. Inside a Custom HTML tag, the variable can be accessed using the {{VARIABLE}} notation.

Conclusion

That’s all there is to it to get started, now try login to your application and you’ll see the identification action get triggered and sent to your analytics. Now your analytics platform can grow as your application grows, without littering the code base with metadata tags.

It’s just as easy to add other actions and variables, and create triggers that fire conditionally based on the value of a variable — all within Tag Manager.

 Hope you liked this post.
You may subscribe to us for more good content for Free.
Best,

Non-Interaction Events in Google Analytics

So what are Non-Interaction Events in Google Analytics?

You already know about event tracking in Google Analytics and using it for everything from downloads to video plays. Maybe you’re using jQuery or Google Tag Manager to capture events.

One thing to note about events is that, by default, events affect the bounce rate. That is, if a user lands on a page and an event is triggered, they are not a bounce (even if they don’t view any subsequent pages). In many cases, that’s what you want: after all, if someone engages with the page in some way, you probably don’t want to count them as a bounce any more.

However, you have control over whether those events affect bounce rate. There’s a parameter you can send with the event data to decide this called the “non-interaction” parameter. In a case where a video auto-plays when someone lands on the page, for example, we might want to set the non-interaction parameter so that the bounce rate of that page isn’t zero.

Flagging Non-Interaction Events

The code for a non-interaction event is just a single parameter you set along with the event data.

For Classic GA:

For Universal Analytics:

Using Google Tag Manager:

Screen Shot 2014-05-05 at 8.14.21 AM

Effect on Metrics

Screen Shot 2014-05-01 at 1.03.19 PMNon-interaction events are mostly referenced in regard to bounce rate, but they actually affect several metrics. Setting the non-interaction parameter has the following effects:

  • Bounce rate and time metrics (session duration and time on page) are no longer affected by the event.
  • The number of total events, unique events, sessions, users, etc. are counted normally.

Give us a shout if you need any help with  Analytics by filling in the form below

Check out our Google Analytics solutions here

Check out our Adobe Analytics solutions here

Google Tag Manager (GTM) for mobile apps

Google Tag Manager (GTM) for Mobile Apps was first announced in August this year and has some great implications for app developers.

Perhaps most notably, the product has the potential to overcome one of the most critical challenges in the business: pushing updates to the user base without having to publish a new version on the app marketplace.

Typically, from the moment an app is shipped it is frozen, and from that point onwards the developer can only make changes to how the app behaves if the user accepts an update. By shipping an app with GTM implemented, configurations and values may be continuously updated by publishing new container versions through the web-based GTM interface.

In this post, we will cover how to get started with GTM for mobile apps and how to implement Universal Analytics tags using the GTM SDK for Android. As a heads up, this will occasionally get pretty technical, however I believe it is important to understand the product from its fundamentals.

Initial Set Up

Before we get started, some initial configuration steps need to be completed. More detailed instructions on these are available in the Google Developers Getting Started guide, but in a nutshell they include:

  • Downloading and adding the GTM library to our app project
  • Ensuring our app can access the internet and the network state
  • Adding a Default container to our app project

We will hold back on that last part, adding a Default container, until we have created some basic tags and are ready to publish. We will revisit the Default container later in this post.

Create an App Container

We need to start off by creating a new container in Google Tag Manager and select Mobile Apps as the type. Typically, we will have one container for each app we manage, where the container name is descriptive of the app itself (e.g. “Scrabble App”). Take note of the container ID on top of the interface (in the format “GTM-XXXX”) as we will need it later in our implementation.

App container for mobile app

Opening a Container

Assuming we have completed the basic steps of adding the Google Tag Manager library to our project, the first thing we need to do before we start using its methods is to open our container.

Similarly to how we would load the GTM javascript on a webpage to access a container and its tags, in an app we need to open a container in some main app entry point before any tags can be executed or configuration values retrieved from GTM. Below is the easiest way of achieving this, as outlined on the Google Developers site:

ContainerOpener.openContainer(
        mTagManager,     // TagManager instance.
        GTM-XXXX”,       // Tag Manager Container ID.
        OpenType.PREFER_NON_DEFAULT,   // Prefer not to get the default container, but stale is OK.
        null,                    // Timeout period. Default is 2000ms.
        new ContainerOpener.Notifier() {       // Called when container loads.
          @Override
          public void containerAvailable(Container container) {
            // Handle assignment in callback to avoid blocking main thread.
            mContainer = container;
          }
        }
    );

Before we talk about what this code does, let’s hash out the different container types to avoid some confusion:

  • Container from network: Container with the most recent tags and configurations as currently published in the GTM interface
  • Saved container: Container saved locally on the device
  • Fresh vs. Stale container Saved container that is less vs. greater than 12 hours old
  • Default container: Container file with default configuration values manually added to the app project prior to shipping

We will talk more about the Default container later on. Back to the code. In this implementation, the ContainerOpener will return the first non-default container available. This means that we prefer to use a container from the network or a saved container, whichever is loaded first, because they are more likely to hold our most updated values. Even if the returned container is Stale it will be used, but an asynchronous network request is also made for a Fresh one. The timeout period, set as the default (2 seconds) above, specifies how long to wait before we abandon a request for a non-Default container and fall back on the Default container instead.

We may change the open type from PREFER_NON_DEFAULT to PREFER_FRESH, which means Google Tag Manager will try to retrieve a Fresh container either from the network or disk. The main difference is hence that a Stale container will not be used if we implement PREFER_FRESH unless no other container is available or the timeout period is exceeded. We may also adjust the timeout period for both PREFER_NON_DEFAULT and PREFER_FRESH, however we should think carefully about whether longer request times negatively affects the user experience before doing so.

Tag Example: Universal Analytics Tags

We have completed the initial set up and know how to access our Google Tag Manager container. Let’s go through a simple example of how to track App Views (screens) within our app using Universal Analytics tags.

Step 1: Push Values to the DataLayer Map

The DataLayer map is used to communicate runtime information from the app to GTM, in which we can set up rules based on key-value pairs pushed into the DataLayer. Users of GTM for websites will recognize the terminology. In our example, we want to push an event whenever a screen becomes visible to a user (In Android, the onStart method is suitable for this). Let’s give this event the value ‘screenVisible’. If we want to push several key-value pairs, we may utilize the mapOf() helper method as demonstrated below. In this case, since we will be tracking various screens, it makes sense to also push a value for the screen name.

public class ExampleActivity extends Activity {

  private static final String SCREEN_NAME = "example screen";
  private DataLayer mDataLayer;

  public void onStart() {
    super.onStart(); 
    mDataLayer = TagManager.getInstance(this).getDataLayer();
    mDataLayer.push(DataLayer.mapOf("event", "screenVisible",
                                                   "screenName", SCREEN_NAME));
  }
//..the rest of our activity code
}

We may then simply paste this code into every activity we want to track as a screen, replacing the SCREEN_NAME string value with the relevant name for each activity (“second screen”, “third screen”, etc.).

Note: the container must be open by the time we push values into the DataLayer or GTM will not be able to evaluate them.

Step 2: Set Up Macros In Google Tag Manager

Simply put, macros are the building blocks that tell GTM where to find certain types of information. Some macros come pre-defined in GTM, such as device language or screen resolution, but we may also create our own. First of all we want to create a Data Layer Variable macro called screenName: this is the name of the screen name value we pass along with the event as demonstrated above.

GTM will then be able to evaluate the screenName macro, which can consequently be used in our tags. If we have not done so already, we may also create a Constant String representing our Analytics property ID at this point. These macros are now at our disposal in all container tags.

Macros for Mobile Apps

Step 3: Configure an App View Tag

Let’s set up our Universal Analytics App View tag. Our configurations are visible in the screenshot below (note the use of our newly created macros). The screen name field value of the App View will be automatically populated and corresponds to what we push to the DataLayer as the value of the screenName macro. The gaProperty macro value specifies which Google Analytics property data should be sent to (by reusing it throughout our container, for every Universal Analytics tag, we can both save time and prevent some critical typos).

Tag Manager app view tag

Step 4: Configure a Firing Rule For Our Tag

Finally, we need to set up the conditions under which the tag should execute. Since we are pushing an event with the value “screenVisible” every time an activity becomes visible, this should be the condition under which our tag should fire, as demonstrated below.

Tag Manager firing rule

Step 5: Save and Publish

We can continue to create other tags at this point. It may be beneficial, for example, to create some Google Analytics Event tags to fire on certain interactions within our app. We should apply the same logic in these instances: We need to push various event values to the DataLayer as interactions occur, and then repeat the steps above to create the appropriate Universal Analytics tags. When we’re happy, all that’s left to do is to create a new version of the container and Publish.

Tag Manager version

As we ship our app with Google Tag Manager implemented, requests will be made to the GTM system to retrieve our tags and configuration values as we discussed earlier.

Hold on, there was one more thing: the Default container!

Default Containers

When we are finished with our initial Google Tag Manager implementation and feel happy with the tags we have created, we are almost ready to ship our app. One question should remain with us at this point: what do we do if our users are not connected to the internet and hence unable to retrieve our tags and configurations from the network? Enter the Default container.

Let’s back up a little bit. In the GTM world, tag creation, configuration, settings, etc. is primarily handled in the web-based GTM interface. The power of this is obvious: we no longer need to rely on our development teams to push code for every change we want to make. Instead, we make changes in the GTM interface, publish them, and our tags and values are updated accordingly for our user base. This of course relies on the ability of our websites or applications to reach the GTM servers so that the updates can take effect. Here things get a bit more tricky for mobile apps, which partly live offline, than for websites.

To ensure that at least some container version is always available to our app, we may add a container file holding our configuration values to the project. This can be a .json file or a binary file, the latter being the required type to evaluate macros at runtime through GTM rules. We may access the binary file of our container through the GTM user interface by going to the Versions section. Here, we should download the binary file for our latest published container version and add it to our project.

create tag manager version

The binary file should be put in a /assets/tagmanager folder and its filename should correspond to our container ID (the file must be located in this folder, and it must be named correctly with our container ID). At this point, we should have both the JAR file and the binary file added to our project as shown below.

Mobile app tag manager files

Once this is done, we are ready to ship the app with our Google Tag Manager implementation. As described earlier, Fresh containers will be requested continuously by the library. This ensures that, as we create new versions of our container and publish them in the web-based GTM interface, our user base will be updated accordingly. As a back-up, without any access to a container from either the network or disk, we still have the Default container stored in a binary file to fall back on.

Summary

Let’s summarize what we have done:

  1. After completing some initial configuration steps, we created a new app container in the web-based GTM interface
  2. We figured out how to open our container as users launch our app, choosing the most suitable opening type and timeout value (taking into consideration user experience and performance)
  3. We then implemented code to push an event to the Data Layer as various screens become visible to our users, setting up a Universal Analytics App View tag in GTM to fire every time this happens
  4. We downloaded the binary file of our container and added it to our app project to be used as a Default container
  5. Lastly, we created and published our container in GTM

We are now ready to ship our application with GTM implemented!

Closing Thoughts

Google Tag Manager for mobile apps can be an incredibly powerful tool. This basic example shows how to implement Universal Analytics using this system but barely scratches the surface of what is possible with highly configurable apps that are no longer frozen. Simply put, getting started with GTM for mobile apps today sets businesses up for success in the future, I recommend trying it out as soon as possible.

I would love to hear your thoughts around Google Tag Manager for mobile apps. What are your plans for (or how are you currently) using it?

Check out our Google Analytics solutions here

Check out our Adobe Analytics solutions here

Say Ola! by filling in the form below.