Using Google Universal Analytics with PhoneGap Apps

Using Google Universal Analytics with PhoneGap Apps

Posted by on Tue, Jul 16, 2013
Filed Under | Google Analytics


We come across unique analytics tracking issues all of the time at Blast.

These range from advanced widget/tool tracking to very detailed data collection for inline listings on a website. Our technical team has encountered many unique situations and we absolutely love the challenge when we take on work that pushes the limits of Google Analytics, and we are able to build a solution that provides value to our clients.

Below is one such unique request that we recently received. We provided a solution for getting mobile app tracking on the PhoneGap framework to work correctly in Universal Analytics.

NOTE: This is a highly technical post for users that are developing their mobile application in PhoneGap and wish to track it successfully using Google’s Universal Analytics.

PhoneGap by Adobe PhoneGap Logois a framework that allows you to build apps using web technologies (html, css, and javascript) and then build them across many mobile platforms.

It is a great way to build mobile apps where you just need to code it once and easily build across seven mobile platforms (currently iOS, Android, Windows Phone 7/8, Blackberry OS, WebOS, Symbian, and Bada).

Tracking usage of your mobile apps is critical to understanding usage patterns and if users are doing what you want them to do. Google Analytics is a great platform for this.

Prior to Google’s Universal Analytics measurement protocol, you were forced to use a plugin for PhoneGap to get data into Classic Google Analytics. This works well, but you can’t take advantage of the new Universal Analytics features like custom dimensions and metrics (and more).

Unfortunately, if you attempt to use Universal Analytics with PhoneGap, you’ll run into a few issues that will prevent it from working. In this blog post, we review the issues and the solution to get Universal Analytics working with PhoneGap mobile apps.

The Challenge

Don’t attempt to use the Mobile App tracking code that Google provides. This code is for when you’ll be coding in native iOS or Android programming languages (Objective-C and Java). Since PhoneGap essentially is rendering a local web page, you should be using the web tracking analytics.js code.

When you use analytics.js, it is assuming that you are loading your web page from an http or https (ssl) protocol. PhoneGap renders pages via the file:// protocol. This is going to cause problems in a few areas. You can’t store cookies with the file:// protocol since there is no domain and the location of the analytics.js file is a relative protocol, which results in the file not being found.

Additionally, there is a bug in version 2.5.0 of PhoneGap that causes an Type Error on iOS. We provide a fix for that here as well.

Custom 4 Step Solution

To get around the file:// protocol issue, we need to do four things.

1) Modify the analytics.js file to remove the code that aborts itself when it doesn’t see either the http or https protocol. If we take the http://www.google-analytics.com/analytics.js file into jsbeautifier.org to make it easier to edit, we have to locate the Oa() function and comment out a line. Note that when Google updates analytics.js, this function may no longer be called Oa() due to changes when they re-compress the file. Here’s the code; comment out the if statement on line 248.
Phone Gap GA UA Fix
2) In PhoneGap v2.5.0 (fixed in later versions), there is a Type Error in iOS when analytics.js executes. This is an issue with navigator.javaEnabled. To fix, comment out line 814:
PhoneGap Type Error iOS GA
3) Since you’ve just made edits to analytics.js, you’ll want to host this file locally as part of your PhoneGap build file. Here’s the snippet you should use to reference an analytics.js file that you now host locally in the root folder of the application:

Note: If Google in the future adjusts analytics.js to work correctly, you’ll still need to adjust the code snippet above since it is currently relying on a relative protocol.

4) You can’t store cookies when using the file:// protocol. There is no domain to store the data with. So, we need to instead turn off cookie storage in Universal Analytics and instead pass in our own clientId value. Here’s where you have an option. You have the following options to consider:

  • You can use the device.uuid API in PhoneGap to grab a UUID
     ga('create', 'UA-XXXXXX-YY', {
     'storage': 'none',
     'clientId':device.uuid
     });
     ga('send', 'pageview', {'page': '/my/page'});
  • You can set your own clientId value if your users are logged in. Google recommends a UUID v4 value.
    ga('create', 'UA-XXXXXX-YY', {
    'storage': 'none',
     'clientId':'92bf24a5-20e5-4181-9778-2835f28c52d8'
     });
     ga('send', 'pageview', {'page': '/my/page'});
  • You could generate a random one and implement logic to store it in localStorage of the browser. (code not shown for this option)

By following the above steps, you’ll have PhoneGap mobile app tracking in place that works with Universal Analytics. If you want to test this out, I’ve created a really simple application that you can compile and reference (hosted on GitHub).

Enjoy this post?

Join the discussion below, subscribe to our RSS feed or share it on the web.

This post was written by:

has written 30 posts on the Web Analytics Blog.

Joe is the Analytics Director and a Partner at Blast Analytics & Marketing. He understands Google Analytics like nobody else and is a master of many programming languages.

Add Joe to your circles on Google+


Tags: , , , ,
  • Roger

    Thanks for the awesome post Joe Christopher! :D

    Everything works fine when I test it from my local browser, but not sure why it doesn’t work from my android phone. I have try put the snippet everywhere I can but still no luck.

    Any suggestion will be greatly appreciated. :)

  • Roger

    My bad, it ends up because i didn’t pass in the 3rd parameter in “ga(‘send’, ‘pageview’, {‘page’: ‘/my/page2′});”.
    Now everything works fine.

    Thanks again for the post man!

  • http://www.blastam.com Joe Christopher

    @disqus_3XOYzgldbl:disqus You are welcome! Thanks for reading our blog!

  • http://www.hippocampus.sk Hippocampus Martin

    Merci beaucoup ;-)

  • chetan

    sir can u pls tell me where to place the analytics.js ,i mean which folder in the phonegap aap

  • KishanRathod

    Why can’t we use Phonegap Google Analytics plugin?

  • http://www.blastam.com Joe Christopher

    You can, for classic analytics (ga.js). If you want to use Google’s new Universal Analytics, the workarounds noted here are required.

  • http://www.blastam.com Joe Christopher

    @disqus_FWYShhQOqR:disqus In my code example, I placed it in the root folder. You should be able to adjust it though.

  • Kenan Unal

    I built an iphone app using Phone Gap 2.9.0. I downloaded analytics.js from github project and modified my html files according to your post. I am testing on my phone. Google has only reported very first access and no real time tracking. Any idea what could be the cause of it. Since Tracking ID’s default URL is my website domain but the iPhone app loads from local file, could that be the problem? Thanks

  • Kenan Unal

    It looks like onDeviceReady() in not right place to call ga(‘create’, ‘UA-40289602-2′, {‘storage’: ‘none’,'clientId’:device.uuid});

    when I replaced the device.uuid some other UUID and moved the script to the top of page, it started to work.

  • http://www.blastam.com Joe Christopher

    @kenan_unal:disqus Thanks for sharing your results on getting it to work in your situation!

  • Tomas van Rijsse

    According to https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference there is no field such as ‘storage’.

    I think it should be ‘cookieDomain’ now. https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#localhost

    I’m still working to get this working, I don’t have errors but I’m missing real time tracking.

  • http://www.blastam.com Joe Christopher

    @tomasvanrijsse:disqus ‘storage’ is a valid field that is used to disable cookies. https://developers.google.com/analytics/devguides/collection/analyticsjs/domains#disableCookies

  • Steve

    Do you know if modifying the Google Analytics code and including that with your packaged app is against the Google Analytics terms of service?

  • http://www.blastam.com Joe Christopher

    @Steve I’m not a lawyer, so I won’t comment on the ToS. We would certainly take down the code from GitHub if they asked. Google has been open about the ability to host your own version of the GA code if you wish – with the risk that you will be out of date as it continues to evolve. Our intent is to help the community in tracking PhoneGap apps in GA and we took the time to figure out how to make that happen.

  • Tomas van Rijsse

    I’m really interested what other form of UUID you’ve come up with which is available before the onDeviceReady.

  • JKF

    Unfortunately I’m not getting this to work, I just tried to quickly duplicate your example. I don’t get any tracking, not when I view the index.html file in my browser, not after doing a phonegap build. I am wondering, what website address should I fill in when registering for a google analytics account. Now Im using a fake one.

  • http://www.sasasoftwaretechnologies.com/ Web Development Company

    I enjoy reading articles that are so quite well-written. This really is great content. You have loaded this with helpful, informative content that any reader can realize.

  • Jèrémy Allíson

    Same here. Requests sent seem fine, but no tracking found on the GA dashboards.

    @joechristopher:disqus, great article. Wish I could get this working… What URL did you use when configuring the GA account?

  • Jèrémy Allíson

    Found the issue on my side, @disqus_iqn1ZvEMij:disqus. I was testing this out from a test ‘”web version” of our Phonegap app, so the requests were actually marked as coming on behalf of my web host. I had another GA property in the same GA account that was configured with that same host, so it was hijacking all tracking requests.

  • Alexander

    I can’t make it to work. I try to use phonegap from 2.5 to 3.0 on ios. Compile by XCode. And use a simulator.

    Do you can help me? How I can see what script send any data to google analytic?

  • Candace Camarillo

    Thanks, Joe! I’m having trouble getting your sample code to send metrics to our analytics account. Did you set up the analytics account as a Website or App? I really appreciate the tutorial.

  • Candace Camarillo

    I’ve confirmed that setting up the analytics account as a Website did the trick.

  • Chris Rogers

    Dear Joe,
    Many thanks for the post, this is the most relevant article for my situation. However I am still having trouble implementing:

    My situation is rather awkward as I am running an old version of PhoneGap – v1.7 across Android iPhone and a mobile site and the results seem to vary, would you know if the out-dated software would be the source of my problem? I am aware that Universal Analytics is in Beta therefore changes all the time. Many thanks Joe

  • http://www.web-tasks.com/services/NationalSEO Best SEO Company

    “we absolutely love the challenge when we take on work that pushes the limits of Google Analytics, and we are able to build a solution that provides value to our clients.”
    Thanks for the information about the Mobile apps…

  • Bram Vandewalle

    Thanks for sharing this info, much appreciated. I managed to get this working, but only in the Realtime view of my new analytics account. Does anyone have any clue what I did wrong?

    What URL should I have used? How can I change the status from “Not Installed” to something else?

  • Paul Eustice

    Hi Joe,

    I’ve just read the Ts&Cs (surprisingly short, actually) and Section 12 specifically says no copying, modification, or adaptation of the tracking code. So, I’d be inclined to think it IS against the terms.

    Have you contacted Google about this at all? You mentioned that they’ve been open to hosting your own version previously, do you have any references?

    Cheers,

    Paul

  • http://www.blastam.com Joe Christopher

    @pauleustice:disqus I don’t have any references. Proceed at your own risk. There is no other option to get it to work unless you want to write your own tracking library leveraging the open measurement protocol specs…

  • Paul Eustice

    I’m toying with the idea of just firing off the HTTP requests manually, if I get any joy I’ll update you.

    I’m using Titanium to wrap a webview but it faces the same problems with running off the file protocol.

  • Mrudula

    When creating the Tracking ID for my PhoneGap app, i gave the Website Url as the url of our production site. When running the application using the analytics.js, no data is logged in the analytics. Am i missing anything ?

  • http://www.sasasoftwaretechnologies.com/ Web Development Company

    Awesome read and it’s nice to get some perspective from someone with experience.

  • Jason Rea

    Awesome post otherwise…

  • Jason Rea

    Does anyone have the code snippet for step 3?

  • Jason Rea

    Aaaah…I see it on your github project. My apologies.

  • Jason Rea

    Do you have to configure your analytics account as a website to get this to work? Configuring it as a mobile app gives more data such as device metrics.

  • http://www.blastam.com Joe Christopher

    @jason_rea:disqus As a website.

  • Jason Rea

    what do you put for the website url when configuring as a website? Does it matter?

  • Jason Rea

    what did you put as the website url?

  • Jason Rea

    did you ever figure this out?

  • http://www.blastam.com Joe Christopher

    It actually doesn’t matter. That value is only used for the in-page analytics feature, which won’t work anyways.

  • Jason Rea

    I created an analytics account as a website and put a random url, then I installed the sample phonegap app on my phone. My analytics report receives no data…..am i missing something?

  • Jason Rea

    Allrighty, thanks. I’ve created an analytics instance as a website with a bogus url, installed the sample code on your github onto my phone, and my GA report shows no data. Is there something I’m missing?

  • http://www.blastam.com Joe Christopher

    Check the real-time report as you may find hits there. Data in the reports will be blank for up to 48 hours on a newly created profile view (but typically just an hour or two). You can also run your phone through a proxy to make sure the hits are going out to GA’s servers correctly…

  • Дмитрий Исаков

    Hi Joe,
    It passed more than 24 hours and still no data. The status in profile is NO DATA GATHERING. What can be the problem?

  • Дмитрий Исаков

    As I understand you dont recommend using Native GA SDK, but use analytics.js. If I understand correctly this will not allow me to track the app installation sources because GA doesnt understand that it is an app.

    Does anyone tried to use ga(‘set’, ‘appName’, ‘App Name’) commands this way?

  • Дмитрий Исаков

    So the question is how can I track the installation and running utm metrics for my app? Anyway I cannot tie website analytics to google play dev console.

  • alurosu

    I’ve used the analytics.js from the example and it works if I load the page in my browser.

    The issue is that when I upload the zip file to phonegap build it does not work anymore. Do you have any idea why?

    Thanks

  • Byron Matto

    Do you see any issue with keeping a local analytics.js file? In the case google changes that file, what steps would you take to ensure that you are not left behind?

  • DalSoft

    Thank you for posting this just what I needed

  • Werner Mesch

    Google says: “If you use the Google Analytics SDK for Android or iOS v2.x or higher, you’re already using Universal Analytics and don’t need to take any further action.”

    https://developers.google.com/analytics/devguides/collection/upgrade/reference/mobile-sdk

    And the Phonegap Plugin for Analytics is based on v2 of the SDK, right?

    http://phonegap.com/blog/build/important-update-to-Google-Analytics-Plugin/

    So is the workaround really needed?

  • http://www.blastam.com Joe Christopher

    @wernermesch:disqus It appears that the plugin is now updated for this, which is great news. As such, it is probably a better idea to use it rather than the method we’ve discussed in this blog post.

  • Harish Kashyap

    Is there any restriction of android version to use it … when i use it with 4.0 version it is working .. but when i installed it on >4.1 version its not working .. anybody have solution??

  • chris

    I have the same issue – works fine from browser but not in cordova – do I need to grant any extra permissions in cordova (whit domain whitelisting?)

  • http://thilak.in Thilak Rao

    I believe this would not work anymore because the hostname of your phonegap app would not match the hostname of your production site.

  • Asifa Haniff

    Where do you get the

    clientId’ from and how do you create it.

  • neilmanuell

    I’m having the same problem, though I’m building locally. works in browser, but analytic.js is not being called from with in phone gap

  • neilmanuell

    I fixed this by a slight modification of the ga script tag
    where it references “/analytics.js” remove the slash so it is “analytics.js”

  • Taylor Nelson

    Does this work for Intel XDK apps as well?

  • GraemeQ

    Oddly enough, I had the same problem. I’ve fixed it from what I can tell but i’ve only done a few tests and not tried full eCommerce stuff or anything (just page views).

    Changes I made:
    (window,document,’script’,'analytics.js’,'ga’)
    In your code, remove the forward slash.

    In the GA create method:

    ga(‘create’, ‘UA-xxxx-yyyy’, {
    ‘storage’: ‘none’,
    ‘clientId’:’1236123123123′,
    ‘cookieDomain’: ‘none’
    });

    Seems to have worked.

  • Vicente Peris

    Thanks for the post Joe Christopher!Very usefull.

    Now I’m trying with ecommerce tracking, but doesn’t works for me, maybe I’m using badly the code.
    I don’t know how to call the ecommerce.js
    ga(‘require’, ‘ecommerce’, ‘ecommerce.js’);
    Every help will be welcome

    Thank you very much



Goal Driven Online Marketing & Analytics
Copyright © 1999-2013 Blast Analytics & Marketing