How to use Google Analytics with Phonegap without a plugin?

Check out the video to see it in action:

http://screencast.com/t/6vkWlZOp

After some research, I found a solution. I came across this thread on the Phonegap Google Group: https://groups.google.com/forum/#!msg/phonegap/uqYjTmd4w_E/YD1QPmLSxf4J
(thanks TimW and Dan Levine!)
In this thread I found that it is possible to use Google Analytics without a plugin. All you have to do is download the ga.js file from Google http://www.google-analytics.com/ga.js (just save the page into your www folder)

Then modify the ga.js file by adding one character to it. Search the ga.js file for the word “file:” and replace it with “_file:”.

In the thread I linked to above, “TimW” explains the reasoning for this:

Essentially, Google Analytics won’t work if its being used from a
file:/// url. In iOS/PhoneGap this is the case. In order to solve this
problem you must first download the ga.js file from google and include
it as part of your local build. You’ll notice the this file is
obfuscated. Search the file for the string “file:” which should occur
only once. When you find it, add an underscore to the beginning (so it
becomes “_file:”). This prevents it matching the protocol of the page
location (which is “file:”).

After you added one character to the ga.js file, simply include this following in the top of your page:

<script type="text/javascript" src="https://stackoverflow.com/questions/11026916/ga.js"></script>
    <script>
 var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-YOUR_ID_HERE']);
    _gaq.push(['_setDomainName', 'none']);
    _gaq.push(['_trackPageview', 'NAME_OF_PAGE']);
    </script>

I tested this on the simulator, and I got a proof that it was working using the Real-Time view in Google Analytics. The simulator was working on iOS 5.0. My phone is still on iOS 4.2, and when I tested it on my device, it didn’t show up on the Real Time tracking.

In the thread, someone mentioned the same issues with Android 4.0+… Hopefully there will be a better solution for this in the future but for now this is the easiest and least complicated way to get basic analytics for my app. It can’t do offline tracking, but that’s kinda creepy anyways.

Even though iOS 4 and Android users are a minority in the market (see pie chart):

http://static7.businessinsider.com/image/4fd65fac6bb3f7925700000f/chart-of-the-day-ios-vs-android-june-2012.jpg

I would stil like to get data from all OS’s.

Leave a Comment