Google analytics not working

14,294 views
Skip to first unread message

Massimo Nicolardi

unread,
Mar 14, 2012, 10:25:04 AM3/14/12
to phon...@googlegroups.com
Hello,

I am trying to install google analytics tracking code on a cordova (1.5.0) application (android) but I have had no success.

I tried to use this code:

<script type="text/javascript">

var _gaq = _gaq || [];

  _gaq.push(['_setAccount', 'UA-xxxxxx-1']);

  _gaq.push(['_setDomainName', 'none']);

   _gaq.push(['_trackPageview','android/home']);

  (function() {

    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;

    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

  })();

</script>


but no pageview gets tracked by analytics.
Have anyone succeeded to track pageviews with analytics?

By the way.. I know that there there is a plugin which do the job but it has not been upgraded for the use with cordova and so I don't think I can use it.

Thanks,
Massimo

johnk

unread,
Mar 14, 2012, 11:05:37 AM3/14/12
to phon...@googlegroups.com
Are you seeing the initial page load show up in analytics and just not the additional pages or are you not seeing anything at all show up in Google Analytics?

If the initial page load shows up but not the additional pages, it would seem that you'd need to ping Google on each additional page load.  Just inserting the script on the main page won't do it.

Are you using something like jquery mobile or sencha touch for partial page loads?

Massimo Nicolardi

unread,
Mar 14, 2012, 12:24:20 PM3/14/12
to phon...@googlegroups.com
Unfortunately I don't see any page view. Not the first nor the others.

Dan Levine

unread,
Mar 24, 2012, 8:26:31 PM3/24/12
to phon...@googlegroups.com
Does anyone have this working?  If so, can you please share your setup?  

I'm having the same issue on both iOS and Android Massimo, any luck?

Shushey

unread,
Mar 25, 2012, 5:08:33 AM3/25/12
to phon...@googlegroups.com
I have the same issue. Can anyone help? Thank you

goangus

unread,
Mar 29, 2012, 10:28:57 AM3/29/12
to phon...@googlegroups.com
Hello All,

I have got this working!

(Assuming you have a PhoneGap 1.5 App working) follow these steps:

  1. Visit here and download the zip file: https://github.com/purplecabbage/phonegap-plugins/
    Or just click here: https://github.com/purplecabbage/phonegap-plugins/zipball/master
  2. In finder (mac) or explorer (windows) add the following files from the zip file into the following directories:
    /android/analytics/www/analytics.js => {project-folder}/assets/www/
    /android/analytics/lib/libGoogleAnalytics.jar => {project-folder}/libs/
  3. In finder/explorer open the project's "src" directory and inside it, create a new directory called "com" (you will probably see a directory in there already, ignore it).
  4. Inside the new "com" directory create a new directory called "phonegap"
  5. Inside "phonegap" create a new directory called "plugins"
  6. Inside plugins create a new directory called "analytics"
  7. From the previously downloaded zip file, take the /android/analytics/src/com/phonegap/plugins/analytics/GoogleAnalyticsTracker.java file and put it into the new "analytics" directory
  8. In eclipse; right click on the libs/libGoogleAnalytics.jar file and hit "Add to Build Path" under "Build Path"
  9. Open up the "res/xml/plugins.xml" file with the text editor and add: "<plugin name="GoogleAnalyticsTracker" value="com.phonegap.plugins.analytics.GoogleAnalyticsTracker"/>" just above "</plugins>"
    This is different to the instructions on github but it is correct, I promise
  10. Open up "src/com.phonegap.plugins.analytics/GoogleAnalyticsTracker.java" in the text editor and replace "import PhoneGap.api.Plugin" with "import org.apache.cordova.api.Plugin;"
  11. Replace "import PhoneGap.api.PluginResult" with "import org.apache.cordova.api.PluginResult;"
  12. Replace "import PhoneGap.api.PluginResult.Status" with "import org.apache.cordova.api.PluginResult.Status;"
    If you can't see those 3 lines, you may see a little "+" symbol next to the "import org.json.JSONArray;" line, just click it to expand the missing text
  13. Open up "assets/www/analytics.js" and replace all instances of "PhoneGap" with "cordova" (easiest way is to do a find/replace all)
  14. At the bottom of the file there is a few lines of code that begin with "PhoneGap.addConstructor(function() {" Select the whole lot and delete them
  15. open your "assets/www/index.html" file and add code at the bottom of this reply to the bottom of your <head> section:
  16. add 
  17. now you can use: 
    window.plugins.analytics.trackPageView("page1.html", function(){alert("Track: success");}, function(){alert("Track: failure");});
    window.plugins.analytics.trackPageView("category", "action", "event", 1, function(){alert("Track: success");}, function(){alert("Track: failure");});

     
    Code for the bottom of your <head> section (maje sure you put it in script tags)

    function bodyLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
    }

    function onDeviceReady() { 
    cordova.addConstructor(function() { 
    cordova.addPlugin('analytics', new Analytics()); 
    },false);
     
    window.plugins.analytics.start("YOUR-ANALYTICS-ID", function(){console.log("Analytics: start success");}, function(){console.log("Analytics: start failure");}) 

    ////////////////


    I really hope this helps someone out. It worked for me after a couple of hours desperately trying to fix it!!!

TimW

unread,
Apr 3, 2012, 8:16:12 PM4/3/12
to phon...@googlegroups.com
I've only tried this in iOS, but here's how I got it working *without* using a plug-in.

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:").

Now include the modified file in your program rather than the remote ga.js file and you'll find that analytics information will start to appear (check the Realtime display - very helpful of debugging).

Let me know if it works on Android.

JGAui

unread,
Apr 4, 2012, 10:58:05 AM4/4/12
to phon...@googlegroups.com
Thanks Tim, that's brilliant!

Dan Levine

unread,
Apr 5, 2012, 2:06:08 AM4/5/12
to phon...@googlegroups.com
Tim, that is awesome, thank you!!  Exactly what I was looking for.  Yes, I can confirm that works on android as well.

Dan

On Tuesday, April 3, 2012 5:16:12 PM UTC-7, TimW wrote:

AlexCD

unread,
Apr 6, 2012, 12:48:23 PM4/6/12
to phonegap
I've got an error in GoogleAnalyticsTracker.java file. Maybe anyone
can help...

Error:
The method start(String, int, Context) in the type
GoogleAnalyticsTracker is not applicable for the arguments (String,
int, CordovaInterface) GoogleAnalyticsTracker.java

On Mar 29, 5:28 pm, goangus <goan...@gmail.com> wrote:
> Hello All,
>
> I have got this working!
>
> (Assuming you have a PhoneGap 1.5 App working) follow these steps:
>
>    1. Visit here and download the zip file:
>    2. In finder (mac) or explorer (windows) add the following files from
>    the zip file into the following directories:
>    /android/analytics/www/analytics.js => {project-folder}/assets/www/
>    /android/analytics/lib/libGoogleAnalytics.jar => {project-folder}/libs/
>    3. In finder/explorer open the project's "src" directory and inside it,
>    create a new directory called "com" (you will probably see a directory in
>    there already, ignore it).
>    4. Inside the new "com" directory create a new directory called
>    "phonegap"
>    5. Inside "phonegap" create a new directory called "plugins"
>    6. Inside plugins create a new directory called "analytics"
>    7. From the previously downloaded zip file, take the /android/analytics/src/com/phonegap/plugins/analytics/GoogleAnalyticsTracker.java
>    file and put it into the new "analytics" directory
>    8. In eclipse; right click on the libs/libGoogleAnalytics.jar file and
>    hit "Add to Build Path" under "Build Path"
>    9. Open up the "res/xml/plugins.xml" file with the text editor and add: "
>    <plugin name="GoogleAnalyticsTracker" value=
>    "com.phonegap.plugins.analytics.GoogleAnalyticsTracker"/>" just above "</
>    plugins>"
>    This is different to the instructions on github but it is correct, I
>    promise
>    10. Open up
>    "src/com.phonegap.plugins.analytics/GoogleAnalyticsTracker.java" in the
>    text editor and replace "import PhoneGap.api.Plugin" with "importorg.apache.cordova.api.Plugin;"
>    11. Replace "import PhoneGap.api.PluginResult" with "import
>     org.apache.cordova.api.PluginResult;"
>    12. Replace "import PhoneGap.api.PluginResult.Status" with "import
>     org.apache.cordova.api.PluginResult.Status;"
>    If you can't see those 3 lines, you may see a little "+" symbol next to
>    the "import org.json.JSONArray;" line, just click it to expand the
>    missing text
>    13. Open up "assets/www/analytics.js" and replace all instances of
>    "PhoneGap" with "cordova" (easiest way is to do a find/replace all)
>    14. At the bottom of the file there is a few lines of code that begin
>    with "PhoneGap.addConstructor(function() {" Select the whole lot and
>    delete them
>    15. open your "assets/www/index.html" file and add code at the bottom of
>    this reply to the bottom of your <head> section:
>    16. add
>    17. now you can use:
>    window.plugins.analytics.trackPageView("page1.html",
>    function(){alert("Track: success");}, function(){alert("Track: failure");});
>    window.plugins.analytics.trackPageView("category", "action", "event", 1,
>    function(){alert("Track: success");}, function(){alert("Track: failure");});
>
>    *Code for the bottom of your <head> section (maje sure you put it in
>    script tags)*
>    *
>    *
>
>    function bodyLoad() {
>
>    document.addEventListener("deviceready", onDeviceReady, false);
>
>    }
>
>      function onDeviceReady() {
>
>    cordova.addConstructor(function() {
>
>    cordova.addPlugin('analytics', new Analytics());
>
>    },false);
>
>    window.plugins.analytics.start("YOUR-ANALYTICS-ID",
>    function(){console.log("Analytics: start success");},
>    function(){console.log("Analytics: start failure");})
>
>    }
>
>    *////////////////*

Chris Kihneman

unread,
Apr 9, 2012, 4:58:16 PM4/9/12
to phon...@googlegroups.com
I have followed the Cordova Plugin Update Guide and there is now support for iOS on Cordova 1.5.0 or better. Again, this is iOS only, not Android. I've got a pull request in now, but you could follow it to my fork to get the plugin now.



I hope this helps someone.


On Wednesday, March 14, 2012 7:25:04 AM UTC-7, Massimo Nicolardi wrote:
On Wednesday, March 14, 2012 7:25:04 AM UTC-7, Massimo Nicolardi wrote:

Shushey

unread,
Apr 16, 2012, 6:02:49 AM4/16/12
to phon...@googlegroups.com
Hi TimW,
 
Thanks for this post and I aim to give it a try; however, I do not know where to include the GA.GS file and how to reference it as part of the build?
 
Please be kind enough to provide a little more information. Cheers.

Shushey

unread,
Apr 16, 2012, 5:20:19 PM4/16/12
to phon...@googlegroups.com
Dan, Could you please provide a sample of how this looks in practice? I have been modifying the 'ga.src' to get it to work with the modified local ga.js file but with no success: ga.src = document.location.protocol + 'file:///android_asset/www/ga.js';

Alternatively, just let me know how to include the modified ga.js file.

Any ideas? Thank you

Dan Levine

unread,
Apr 16, 2012, 8:46:44 PM4/16/12
to phon...@googlegroups.com
You download the ga.js file, update the source as Tim mentions, save it locally (eg into a scripts folder), and then add something like this in your index.html file:

        <script type="text/javascript" src="scripts/ga.js"></script>

Dan


--
You received this message because you are subscribed to the Google
Groups "phonegap" group.
To post to this group, send email to phon...@googlegroups.com
To unsubscribe from this group, send email to
phonegap+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/phonegap?hl=en?hl=en
 
For more info on PhoneGap or to download the code go to www.phonegap.com



--

Dan Levine | CTO
t    @styleseat / @danlevine



Intovate

unread,
Apr 17, 2012, 3:52:58 AM4/17/12
to phon...@googlegroups.com
Dan, thanks for the reply and I will give it a try. It looks like I was trying to over complicate things, as I thought that I would also have to ammend the 'ga.src' in the Google script. Hopefully, this post will help anyone that is potentially as dense as me.

For more options, visit this group at
http://groups.google.com/group/phonegap?hl=en?hl=en
 
For more info on PhoneGap or to download the code go to www.phonegap.com

Shushey

unread,
Apr 17, 2012, 3:30:00 PM4/17/12
to phon...@googlegroups.com
Hi Dan,

I am still not getting it and I have included the amended 'ga.gs' file that looks like this "_file:"

Added the 'ga.gs' like this within index.html <script type="text/javascript" charset="utf-8" src="ga.js"></script> //I can see the js file  linked correctly in Dreamweaver

Then I amended the Google script like this:

function onDeviceReady() {
 var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'MY-TRACKING-CODE']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = document.location.protocol + 'file:///android_asset/www/ga.js'; // I have tried a number of combinations here but no joy
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
}

Any ideas? Thank you

On Tuesday, 17 April 2012 01:46:44 UTC+1, Dan Levine wrote:

For more options, visit this group at
http://groups.google.com/group/phonegap?hl=en?hl=en
 
For more info on PhoneGap or to download the code go to www.phonegap.com

Dan Levine

unread,
Apr 17, 2012, 3:57:29 PM4/17/12
to phon...@googlegroups.com
Sure, let me walk through it.

First off, I'm assuming your mentions of 'ga.gs' were typos of 'ga.js'.

The lines of code in the javascript block that starts with "(function() {" a self-invoked function.  In one step you are defining a function and then calling it. 

What that function is doing is (1) creating a script tag in the DOM, (2) setting the src of that script tag to the file, and (3) adding that script tag to the page.  This is generically called dynamically load javascript files.  There are many reasons to do this such tuning the performance/loading of the JS and matching the http or https protocol of the page.  Since we don't care so much about those things in this case, the entire self-invoked function is actually a duplicate of the <script> tag you've added to the page.  So you can get rid of all of that.

The whole js block for me looks something like this:


<script type="text/javascript" src="scripts/ga.js"></script>
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXXX']);
_gaq.push(['_setDomainName', 'none']);
_gaq.push(['_trackPageview', 'homepage']);
</script>


I'm not sure if _setDomainName = none is required, but that is the first way I tried it and it works for me.

FYI, that _gaq stuff is a helper pattern for dynamically communicating with a JS function without blocking on its loading.  Instead of calling something like googleAnalyticsObjects.trackPageview('homepage') [which would get an error if the script hadn't been loaded yet], this pattern uses a js array [] as a queue, filling it with actions which the ga script objects checks when its loaded and then processes all of those actions.

Hope this helps.

Dan








For more options, visit this group at
http://groups.google.com/group/phonegap?hl=en?hl=en
 
For more info on PhoneGap or to download the code go to www.phonegap.com

Shushey

unread,
Apr 18, 2012, 2:43:46 PM4/18/12
to phon...@googlegroups.com
Excellent, that worked! Thanks for all your help.

AlexCD

unread,
Apr 18, 2012, 4:02:53 PM4/18/12
to phonegap
Fixed the error "The method start(String, int, Context)..." in
GoogleAnalyticsTracker.java file with the help of goangus.

What you need to do is open the "src/com.phonegap.plugins.analytics/
GoogleAnalyticsTracker.java" file and find the function:

private void start(String accountId) - should be on or around line
61

replace the function with:

private void start(String accountId) {
tracker.start(accountId, DISPATCH_INTERVAL, (Context) this.ctx);
}

To get rid of the warning, just remove the line

import android.util.Log

from the top of the same file.

If you still get an error, open "src/com.phonegap.plugins.analytics/
GoogleAnalyticsTracker.java" in Java Editor, go to
private void start(String accountId) {
tracker.start(accountId, DISPATCH_INTERVAL, (Context) this.ctx);
}
put your mouse over "(Context)" and choose the first option
import.Context.

That's it.

Adrian

unread,
Apr 23, 2012, 3:23:42 AM4/23/12
to phonegap
Excellent explanation.

Works fine on iOS 5.x and Android 2.x but seems to fail on Android 4.x
and iOS 4.x.

Did anyone managed to make it work on those versions ?

Thanks by advance.

Adrian
> >> On Mon, Apr 16, 2012 at 2:20 PM, Shushey <stevenjhal...@gmail.com> wrote:
>
> >>> Dan, Could you please provide a sample of how this looks in practice? I
> >>> have been modifying the 'ga.src' to get it to work with the modified local
> >>> ga.js file but with no success: ga.src = document.location.protocol +
> >>> 'file:///android_asset/www/ga.**js';
> >>>>>>    _gaq.push(['_trackPageview','**a**ndroid/home']);
>
> >>>>>>   (function() {
>
> >>>>>>     var ga = document.createElement('**script**'); ga.type =
> >>>>>> 'text/javascript'; ga.async = true;
>
> >>>>>>     ga.src = ('https:' == document.location.protocol ? 'https://ssl':
> >>>>>> 'http://www') + '.google-analytics.com/ga.js';
>
> >>>>>>     var s = document.getElementsByTagName(****'script')[0];
> >>>>>> s.parentNode.insertBefore(ga, s);
>
> >>>>>>   })();
> >>>>>> </script>
>
> >>>>>> but no pageview gets tracked by analytics.
> >>>>>> Have anyone succeeded to track pageviews with analytics?
>
> >>>>>> By the way.. I know that there there is a plugin which do the job but
> >>>>>> it has not been upgraded for the use with cordova and so I don't think I
> >>>>>> can use it.
>
> >>>>>> Thanks,
> >>>>>> Massimo
>
> >>>>> On Wednesday, March 14, 2012 7:25:04 AM UTC-7, Massimo Nicolardi wrote:
>
> >>>>>> Hello,
>
> >>>>>> I am trying to install google analytics tracking code on a cordova
> >>>>>> (1.5.0) application (android) but I have had no success.
>
> >>>>>> I tried to use this code:
>
> >>>>>>  <script type="text/javascript">
>
> >>>>>> var _gaq = _gaq || [];
>
> >>>>>>   _gaq.push(['_setAccount', 'UA-xxxxxx-1']);
>
> >>>>>>   _gaq.push(['_setDomainName', 'none']);
>
> >>>>>>    _gaq.push(['_trackPageview','**a**ndroid/home']);
>
> >>>>>>   (function() {
>
> >>>>>>     var ga = document.createElement('**script**'); ga.type =
> >>>>>> 'text/javascript'; ga.async = true;
>
> >>>>>>     ga.src = ('https:' == document.location.protocol ? 'https://ssl':
> >>>>>> 'http://www') + '.google-analytics.com/ga.js';
>
> >>>>>>     var s = document.getElementsByTagName(****'script')[0];
> >>>>>> s.parentNode.insertBefore(ga, s);
>
> >>>>>>   })();
> >>>>>> </script>
>
> >>>>>> but no pageview gets tracked by analytics.
> >>>>>> Have anyone succeeded to track pageviews with analytics?
>
> >>>>>> By the way.. I know that there there is a plugin which do the job but
> >>>>>> it has not been upgraded for the use with cordova and so I don't think I
> >>>>>> can use it.
>
> >>>>>> Thanks,
> >>>>>> Massimo
>
> >>>>>>  --
> >>> You received this message because you are subscribed to the Google
> >>> Groups "phonegap" group.
> >>> To post to this group, send email to phon...@googlegroups.com
> >>> To unsubscribe from this group, send email to
> >>> phonegap+unsubscribe@**googlegroups.com<phonegap%2Bunsu...@googlegroups.com>
> >>> For more options, visit this group at
> >>>http://groups.google.com/**group/phonegap?hl=en?hl=en<http://groups.google.com/group/phonegap?hl=en?hl=en>
>
> >>> For more info on PhoneGap or to download the code go towww.phonegap.com
>
> >> --
> >> -
> >> Dan Levine | CTO
> >> w  http://www.styleseat.com<http://styleseat.com/>
> >> t    @styleseat / @danlevine
> >> p   415.637.1468
>
> >>   --
> > You received this message because you are subscribed to the Google
> > Groups "phonegap" group.
> > To post to this group, send email to phon...@googlegroups.com
> > To unsubscribe from this group, send email to
> > phonegap+u...@googlegroups.com
> > For more options, visit this group at
> >http://groups.google.com/group/phonegap?hl=en?hl=en
>
> > For more info on PhoneGap or to download the code go towww.phonegap.com
>
> --
> -
> Dan Levine | CTO
> w  http://www.styleseat.com<http://styleseat.com/>

leonard nero

unread,
May 4, 2012, 8:38:50 PM5/4/12
to phon...@googlegroups.com
Yes, obiviusly there is a problem with some android browser and i thing its not wise to get Ga.js in localy cuz you never know when google will change something inside the code. 
But that is not real problem, real problem is with offline applications and their tracking. When u are not connected on internet or wateva, google analitycs dont send offline tracking of your application.

So i think that use of goangus method is better.

Nono

unread,
May 27, 2012, 2:03:05 PM5/27/12
to phon...@googlegroups.com
Hi goangus

I'm developing an Android app using Phonegap and Sencha and I want to add google analytics
I followed your instructions for using the plugin.

When I execute:
window.plugins.analytics.start("UA–XXXXXXXX–1", function(){console.log("Analytics: start success");}, function(){console.log("Analytics: start failure");}) 
I've got the "Analytics: start success" in the console.

And then when I execute:
window.plugins.analytics.trackPageView("page1.html", function(){alert("Track: success");}, function(){alert("Track: failure");}); 
The alert "Track: success" is done

But when I check on google analytics in real time it says there is no visitor.

Is the plugin supposed to work in real time?
If yes, why I can't see it in google analytics?

Cheers

Nono

unread,
May 27, 2012, 2:50:00 PM5/27/12
to phonegap
Hi  goangus ,




I'm developing an Android app using Phonegap and Sencha and I want to
add google analytics
I followed your instructions for using the plugin.




When I execute:
window.plugins.analytics.start("UA–XXXXXXXX–1", function()
{console.log("Analytics: start success");}, function()
{console.log("Analytics: start failure");})
I've got the "Analytics: start success" in the console.




And then when I execute:
window.plugins.analytics.trackPageView("page1.html", function()
{alert("Track: success");}, function(){alert("Track: failure");});
The alert "Track: success" is done




But when I check on google analytics in real time it says there is no
visitor.




Is the plugin supposed to work in real time?
If yes, why I can't see it in google analytics?
Do I do something wrong?




Cheers

mictam

unread,
Jul 23, 2012, 2:34:09 PM7/23/12
to phon...@googlegroups.com
I just wanted to chime in here because after some challenges I got this working. I followed all the directions that goangus wrote out but couldn't get it going. I am an admitted newbie. To finally get it to work I added an onclick event to a button and removed the alerts. Everything was done like goangus wrote, but I added onclick="window.plugins.analytics.trackPageView('MobileTestPage');"

I have no idea if this incorrect, but it finally worked.


On Wednesday, March 14, 2012 7:25:04 AM UTC-7, Massimo Nicolardi wrote:

mictam

unread,
Jul 23, 2012, 7:48:54 PM7/23/12
to phon...@googlegroups.com
Oh and this is on Android. iOS I'm still working on.

Nikola Vitas

unread,
Jul 25, 2012, 9:59:03 AM7/25/12
to phon...@googlegroups.com
Never mind, it does work for me as well. Well done, great solution.

On Tuesday, July 24, 2012 3:40:33 PM UTC-4, Nikola Vitas wrote:
I'm having a bit of a hard time getting this to work...I followed the instructions but nothing is being sent. So I dug a little deeper and it turns out that google analytics needs cookies to be enabled. 

This is straight from stack overflow: 

"cookies are proprietary to HTTP, and when you run something from file://, you're not using the HTTP protocol.

Since you're not able to set cookies, ga.js refuses to send the _utm.gif request to Google's servers. No cookies get set; no request is sent to google, so nothing is logged in GA."

In my case nothing is being sent and I'm wondering if the cookies have something to do with it. Has anyone else had this problem or has it worked for the ones that tried...

Michael SBCERA

unread,
Jul 25, 2012, 6:30:32 PM7/25/12
to phon...@googlegroups.com
Anyone have any thoughts on why this is working as an onclick event in Android, but not iOS? I'm using Cordova 1.8.1 jQueryMobile 1.1.1 and jQuery 1.7 if that helps.

I have in onDeviceReady:

            var googleAnalytics = window.plugins.googleAnalyticsPlugin;

            googleAnalytics.startTrackerWithAccountID("UA-MyCode");

            googleAnalytics.trackPageview('/MobileiOS');

Which is working and I see in Analytics.

After <body onload="onLoad()"> I have a button that navigates correctly to a page and also has onclick="googleAnalytics.trackPageview('/TestMobileiOS');"

Nothing in Analytics.

onLoad has:

        function onLoad(){

            document.addEventListener("deviceready", onDeviceReady, false);


        }

Thanks for any help.

Cuadraman

unread,
Aug 18, 2012, 10:37:29 PM8/18/12
to phon...@googlegroups.com
Can someone share their working cordova 1.9 GA application in a git?

doubledutch

unread,
Sep 12, 2012, 3:57:43 AM9/12/12
to phon...@googlegroups.com
I followed your steps (I think...) but can't get to work - can you suggest what I'm doing wrong as I am not sure that the way I made the javascript changes is correct AND when I make the changes to the java file eclipse tells me that LegacyContext.getAppplicationContext has been depreciated...

JAVA CODE

    private void start(String accountId) {
        tracker.start(accountId, DISPATCH_INTERVAL, this.ctx.getApplicationContext());
    }

JAVASCRIPT CODE

/*
 * cordova is available under *either* the terms of the modified BSD license *or* the
 * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
 *
 * Copyright (c) 2006-2011 Worklight, Ltd.
 */


/**
 * Constructor
 */
function Analytics() {
}

/**
 * Initialize Google Analytics configuration
 *
 * @param accountId            The Google Analytics account id
 * @param successCallback    The success callback
 * @param failureCallback    The error callback
 */
//Analytics.prototype.start

cordova.analytics.start = function(accountId, successCallback, failureCallback) {
    return cordova.exec(
                successCallback,             
                failureCallback,                       
                'GoogleAnalyticsTracker',               
                'start',                               
                [accountId]);
};

/**
 * Track a page view on Google Analytics
 * @param key                The name of the tracked item (can be a url or some logical name).
 *                             The key name will be presented in Google Analytics report. 
 * @param successCallback    The success callback
 * @param failureCallback    The error callback
 */
// Analytics.prototype.trackPageView
cordova.analytics.trackPageView = function(key, successCallback, failureCallback) {
    return cordova.exec(
                successCallback,           
                failureCallback,       
                'GoogleAnalyticsTracker',
                'trackPageView',       
                [key]);                   
};

/**
 * Track an event on Google Analytics
 * @param category            The name that you supply as a way to group objects that you want to track
 * @param action            The name the type of event or interaction you want to track for a particular web object
 * @param label                Provides additional information for events that you want to track (optional)
 * @param value                Assign a numerical value to a tracked page object (optional)

 * @param successCallback    The success callback
 * @param failureCallback    The error callback
 */

//Analytics.prototype.trackEvent
cordova.analytics.trackEvent = function(category, action, label, value, successCallback, failureCallback){
    return cordova.exec(
                successCallback,           
                failureCallback,       
                'GoogleAnalyticsTracker',
                'trackEvent',       
                [
                    category,
                    action,
                    typeof label === "undefined" ? "" : label,
                    (isNaN(parseInt(value,10))) ? 0 : parseInt(value, 10)
                ]);                   
};

Analytics.prototype.setCustomVar = function(index, label, value, scope, successCallback, failureCallback){
    return cordova.exec(
                successCallback,           
                failureCallback,       
                'GoogleAnalyticsTracker',
                'setCustomVariable',       
                [
                    (isNaN(parseInt(index,10))) ? 0 : parseInt(index, 10),
                    label,
                    value,
                    (isNaN(parseInt(scope,10))) ? 0 : parseInt(scope, 10)
                ]);                   
};

/*

        cordova.addConstructor(function() {
            cordova.addPlugin('analytics', new Analytics());
            InitAnalytics();
        },false);
*/       

cordova.analytics = new Analytics();

Michael SBCERA

unread,
Sep 21, 2012, 11:34:01 AM9/21/12
to phon...@googlegroups.com
Did you get it running? I have it working 1.8.1 and it also registers onclick events. I can try to help if you don't have it working.

ThePackers

unread,
Oct 5, 2012, 5:03:00 PM10/5/12
to phon...@googlegroups.com
Did it works on Android version 4+?

Panabee

unread,
Oct 23, 2012, 5:36:30 PM10/23/12
to phon...@googlegroups.com
Did anyone get this working on PG 2.0?

Thanks!

nocksf

unread,
Nov 1, 2012, 3:01:06 PM11/1/12
to phon...@googlegroups.com
I have a "GoogleAnalytics" group under Plugins that contains my .m and .h file.  Inside the GoogleAnalytics group I have another group 'GoogleSDK' that contains references to headers from the GoogleAnalyticsiOS_2.0beta3 download - GAI.h, GAITracker.h, GAITrackedViewController.h, GAITransaction.h, and GAITransactionItem.h.  The path to GoogleAnalyticsiOS_2.0beta3/Library is also in my BuildSettings - LibrarySearchPaths.

I went through a bunch of other things getting xcode 4.5 and PG2.1 to play together from my prior releases, but I think all of those were separate to getting analytics working.

On Thursday, November 1, 2012 3:46:07 AM UTC-7, Alex Flynn wrote:
I have not been able to get this to build without link errors. Can you provide your plugins folder?

On Monday, 29 October 2012 22:18:34 UTC, nocksf wrote:
I had been running with PG 1.7 and an older version of the plugin - where http://stackoverflow.com/questions/8097015/step-by-set-to-get-google-analytics-working-in-phonegap-1-2-0-on-ios-phonegapal helped a lot. From that starting point, here's what I just did to get it running on PG2.1, latest Google SDK, and xcode/ios.  Sorry, it's not completely comprehensive, but it might help you down the path if you had it working with an older version.

Got it basically working with PG 2.1.  
- downloaded the current SDK from Google (note there doesn't seem to be support for CustomVariables anymore).
- put the header files (5) from the Library dir in a plugins folder
- changed GoogleAnalyticsPlugin.h to this:

#import <Foundation/Foundation.h>
#import "GAI.h"
#import <Cordova/CDV.h>
@interface GoogleAnalyticsPlugin : CDVPlugin  {
}

- (void) trackerWithTrackingId:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
- (void) trackEventWithCategory:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
- (void) trackView:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;

@end

Changed GoogleAnalyticsPlugin.m to this:

#import "GoogleAnalyticsPlugin.h"
// Dispatch period in seconds
static const NSInteger kGANDispatchPeriodSec = 2;
@implementation GoogleAnalyticsPlugin
- (void) trackerWithTrackingId:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
NSString* accountId = [arguments objectAtIndex:0];
    [GAI sharedInstance].debug = YES;
    [GAI sharedInstance].dispatchInterval = kGANDispatchPeriodSec;
    [GAI sharedInstance].trackUncaughtExceptions = YES;
    [[GAI sharedInstance] trackerWithTrackingId:accountId];
}
- (void) trackEventWithCategory:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
NSString* category = [options valueForKey:@"category"];
NSString* action = [options valueForKey:@"action"];
NSString* label = [options valueForKey:@"label"];
NSNumber* value = [options valueForKey:@"value"];
if (![[GAI sharedInstance].defaultTracker trackEventWithCategory:category
  withAction:action
  withLabel:label
  withValue:value]) {
    // Handle error here
    NSLog(@"GoogleAnalyticsPlugin.trackEvent Error::");

  }
NSLog(@"GoogleAnalyticsPlugin.trackEvent::%@, %@, %@, %@",category,action,label,value);
}

- (void) trackView:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
NSString* pageUri = [arguments objectAtIndex:0];
if (![[GAI sharedInstance].defaultTracker trackView:pageUri]) {
// TODO: Handle error here
}
}

- (void) hitDispatched:(NSString *)hitString
{
NSString* callback = [NSString stringWithFormat:@"window.plugins.googleAnalyticsPlugin.hitDispatched(%d);",  hitString];
[ self.webView stringByEvaluatingJavaScriptFromString:callback];
}
@end

Changed GoogleAnalyticsPlugin.js to this (some of this is just a style preference from the original):

if (!window.GA) {
    window.GA = {
        trackerWithTrackingId: function(id) {
            PhoneGap.exec("GoogleAnalyticsPlugin.trackerWithTrackingId",id);
        },
        trackView: function(pageUri) {
            PhoneGap.exec("GoogleAnalyticsPlugin.trackView",pageUri);
        },
        trackEventWithCategory: function(category,action,label,value) {
            var options = {category:category,
            action:action,
            label:label,
                value:value};
            PhoneGap.exec("GoogleAnalyticsPlugin.trackEventWithCategory",options);
        },
        hitDispatched: function(hitString) {
            //console.log("hitDispatched :: " + hitString);
        },
        trackerDispatchDidComplete: function(count) {
            //console.log("trackerDispatchDidComplete :: " + count);
        }
    }

}

then called my new js functions from my app.  I had to create a new property in Analytics (I was using our existing id for web analytics before), but I can now see my mobile analytics on the real-time GA page.

abhishek sharma

unread,
Nov 19, 2012, 7:17:56 AM11/19/12
to phon...@googlegroups.com
thanx mate...I wish could say I love you. :D
m trying this in a minute...
  1. now you can use: 

  1. window.plugins.analytics.trackPageView("page1.html", function(){alert("Track: success");}, function(){alert("Track: failure");});
  1. window.plugins.analytics.trackPageView("category", "action", "event", 1, function(){alert("Track: success");}, function(){alert("Track: failure");});

     
    Code for the bottom of your <head> section (maje sure you put it in script tags)

    function bodyLoad() {
  1. document.addEventListener("deviceready", onDeviceReady, false);
    }

    function onDeviceReady() { 
  1. cordova.addConstructor(function() { 
    cordova.addPlugin('analytics', new Analytics()); 
  1. },false);

Adam Baldwin

unread,
Nov 19, 2012, 12:15:15 PM11/19/12
to phon...@googlegroups.com, tim.j.w...@gmail.com
@Tim - Has anyone figured out why the non-plugin solution does not work with Android 4.0+?


On Tuesday, April 3, 2012 6:16:12 PM UTC-6, TimW wrote:
I've only tried this in iOS, but here's how I got it working *without* using a plug-in.

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:").

Now include the modified file in your program rather than the remote ga.js file and you'll find that analytics information will start to appear (check the Realtime display - very helpful of debugging).

Let me know if it works on Android.

Phil Merrell

unread,
Jan 10, 2013, 10:54:05 AM1/10/13
to phon...@googlegroups.com
Tried out GoogleAnalytics plugin with Cordova 2.3 and couldn't get it to work.  I have it working in 2.2 and curious if anyone has it working 2.3... 

On Tuesday, December 18, 2012 11:30:43 PM UTC-7, Benjamin Bjurstrom wrote:
@Alex,
I had the same issue as you. What fixed it for me was discovering that Google Analytics SDK 2.0+ uses different frameworks then the previous versions. Be sure to include the following.
  • CoreData.framework
  • SystemConfiguration.framework
You should also be able to remove libsqlite3.0.dylib unless another part of your app requires it.

Giacomo Balli

unread,
Jan 10, 2013, 12:51:26 PM1/10/13
to phonegap
if you provide the error it would make it easier to help you...

On Jan 10, 7:54 am, Phil Merrell <philmerr...@boisestate.edu> wrote:
> Tried out GoogleAnalytics plugin with Cordova 2.3 and couldn't get it to
> work.  I have it working in 2.2 and curious if anyone has it working 2.3...
>
>
>
>
>
>
>
> On Tuesday, December 18, 2012 11:30:43 PM UTC-7, Benjamin Bjurstrom wrote:
>
> > @Alex,
> > I had the same issue as you. What fixed it for me was discovering that
> > Google Analytics SDK 2.0+ uses different frameworks then the previous
> > versions. Be sure to include the following.
>
> >    - CoreData.framework
> >    - SystemConfiguration.framework
>
> > You should also be able to remove libsqlite3.0.dylib unless another part
> > of your app requires it.
>
> > On Thursday, November 1, 2012 3:46:07 AM UTC-7, Alex Flynn wrote:
>
> >> I have not been able to get this to build without link errors. Can you
> >> provide your plugins folder?
>
> >> On Monday, 29 October 2012 22:18:34 UTC, nocksf wrote:
>
> >>> I had been running with PG 1.7 and an older version of the plugin -
> >>> where
> >>>http://stackoverflow.com/questions/8097015/step-by-set-to-get-google-...a lot. From that starting point, here's what I just did to get it

Phil Merrell

unread,
Jan 10, 2013, 1:04:51 PM1/10/13
to phon...@googlegroups.com
Thanks for the reply... I really appreciate it.

As for errors, I guess that's part of the problem... no errors are logged and the project builds just fine.  I was just curious if anyone else had tried it yet with Cordova 2.3.  However I know it's certainly a possibility that I integrated it incorrectly.

I went through the same steps to get it working in 2.2, but with no luck.

  • I added CoreData and SystemConfiguration libraries
  • I added the necessary items to the cordova.plist (which has changed in 2.3 to config.xml)
  • I added the GoogleAnalytics.js file to my index.html
  • I called window.GA.trackerWithTrackingId("UA-xxxxxxxx-x"); in my 'deviceready' event.
The result is that 'deviceready' is logged, but no analytics are logged.

Michael SBCERA

unread,
Feb 5, 2013, 6:05:07 PM2/5/13
to phon...@googlegroups.com
I am also having the same problem now. Everything seems to work with no errors but analytics are never registered. With previous versions I could see in real time my apps analytics.

This is the log I am receiving:

SBCERAApp[3681:15e03] GoogleAnalytics 2.0b3 -[GAIDispatcher internalCreateTimer] (GAIDispatcher.m:195) DEBUG: Created timer to fire every 2.0s

2013-02-05 15:02:11.871 SBCERAApp[3681:15e03] Hit URL: http://www.google-analytics.com/collect

2013-02-05 15:02:11.872 SBCERAApp[3681:15e03]     Method: POST

2013-02-05 15:02:11.872 SBCERAApp[3681:15e03]     Header User-Agent: GoogleAnalytics/2.0b3 (iPhone Simulator; U; CPU iPhone OS 6.1 like Mac OS X; en-us)

2013-02-05 15:02:11.872 SBCERAApp[3681:15e03]     Header Content-Length: 179

2013-02-05 15:02:11.873 SBCERAApp[3681:15e03]     Header Content-Type: application/x-www-form-urlencoded; charset=UTF-8

2013-02-05 15:02:11.873 SBCERAApp[3681:15e03]     Body: ul=en&an=SBCERAApp&_v=mi1b3&cid=2b423497187b5924ff1b5802d640e2a2&sc=start&t=appview&sd=24-bit&sr=320x480&cd=%2FMobileiOS&tid=UA-26017499-1&v=1&av=1.0&qt=2018&z=3432372163228806075

2013-02-05 15:02:11.964 SBCERAApp[3681:15e03] GoogleAnalytics 2.0b3 -[GAIDispatcher dispatchComplete:withStartTime:withRetryNumber:withResponse:withData:withError:] (GAIDispatcher.m:392) DEBUG: Hit /GAIHit/p20 dispatched (90ms): HTTP status 200

2013-02-05 15:02:11.968 SBCERAApp[3681:15e03] GoogleAnalytics 2.0b3 -[GAIDispatcher dispatchComplete:withStartTime:withRetryNumber:withResponse:withData:withError:] (GAIDispatcher.m:413) DEBUG: Successfully dispatched hit /GAIHit/p20 (0 retries).

2013-02-05 15:02:11.969 SBCERAApp[3681:15e03] Hit URL: http://www.google-analytics.com/collect

2013-02-05 15:02:11.969 SBCERAApp[3681:15e03]     Method: POST

2013-02-05 15:02:11.969 SBCERAApp[3681:15e03]     Header User-Agent: GoogleAnalytics/2.0b3 (iPhone Simulator; U; CPU iPhone OS 6.1 like Mac OS X; en-us)

2013-02-05 15:02:11.970 SBCERAApp[3681:15e03]     Header Content-Length: 172

2013-02-05 15:02:11.970 SBCERAApp[3681:15e03]     Header Content-Type: application/x-www-form-urlencoded; charset=UTF-8

2013-02-05 15:02:11.970 SBCERAApp[3681:15e03]     Body: ul=en&an=SBCERAApp&_v=mi1b3&cid=2b423497187b5924ff1b5802d640e2a2&t=appview&sd=24-bit&sr=320x480&cd=HTTabMobileiOS&tid=UA-26017499-1&v=1&av=1.0&qt=2098&z=3432372163228806076

2013-02-05 15:02:12.020 SBCERAApp[3681:15e03] GoogleAnalytics 2.0b3 -[GAIDispatcher dispatchComplete:withStartTime:withRetryNumber:withResponse:withData:withError:] (GAIDispatcher.m:392) DEBUG: Hit /GAIHit/p21 dispatched (49ms): HTTP status 200

2013-02-05 15:02:12.022 SBCERAApp[3681:15e03] GoogleAnalytics 2.0b3 -[GAIDispatcher dispatchComplete:withStartTime:withRetryNumber:withResponse:withData:withError:] (GAIDispatcher.m:413) DEBUG: Successfully dispatched hit /GAIHit/p21 (0 retries).

2013-02-05 15:02:12.022 SBCERAApp[3681:15e03] GoogleAnalytics 2.0b3 -[GAIDispatcher dispatchComplete:withStartTime:withRetryNumber:withResponse:withData:withError:] (GAIDispatcher.m:420) DEBUG: Pending hit queue drained.

2013-02-05 15:02:12.023 SBCERAApp[3681:15e03] GoogleAnalytics 2.0b3 -[GAIDispatcher cancelTimer] (GAIDispatcher.m:224) DEBUG: Canceled timer with interval 2.0s

 

Ryan Hanna

unread,
Feb 13, 2013, 7:03:21 AM2/13/13
to phon...@googlegroups.com
I followed the instructions for 2.2 and the key thing that made it work for me was nocksf's comment about setting up a new property in Analytics. I was previously using the non-plugin approach and the ga.js. With this my Analytics were setup as a website. M new Analytics is a Mobile App and I am seeing the realtime results. 

Michael SBCERA

unread,
Feb 19, 2013, 11:27:33 AM2/19/13
to phon...@googlegroups.com
Did you set up a new property for mobile devices in Google Analytics?

On Mon, Feb 18, 2013 at 5:06 AM, <sheetal...@gmail.com> wrote:

I did all the steps, copied google analytics folder into plugins, added key to plist, replaced PhoneGap.exec with cordova.exec but still getting error plugin not found or not part of CVDplugin....please help its really urgent...using cordova 2.2.0

--
-- You received this message because you are subscribed to the Google
Groups "phonegap" group.
To post to this group, send email to phon...@googlegroups.com
To unsubscribe from this group, send email to

For more options, visit this group at
http://groups.google.com/group/phonegap?hl=en?hl=en
 
For more info on PhoneGap or to download the code go to www.phonegap.com
 
To compile in the cloud, check out build.phonegap.com
---
You received this message because you are subscribed to the Google Groups "phonegap" group.
To unsubscribe from this group and stop receiving emails from it, send an email to phonegap+u...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Madhan Kumar

unread,
Oct 29, 2014, 6:28:55 PM10/29/14
to phon...@googlegroups.com
Hi Dan, 

Thanks for these. I made the same changes but it's not working in Android alone. iOS and Surface is perfectly fine. But not Android. Any thoughts please? 

Regards,
Madhan


On Wednesday, 4 April 2012 23:06:08 UTC-7, Dan Levine wrote:
Tim, that is awesome, thank you!!  Exactly what I was looking for.  Yes, I can confirm that works on android as well.

Dan

Madhan Kumar

unread,
Oct 29, 2014, 6:29:17 PM10/29/14
to phon...@googlegroups.com, tim.j.w...@gmail.com
Hi Tim, 

Thanks for these. I made the same changes but it's not working in Android alone. iOS and Surface is perfectly fine. But not Android. Any thoughts please? 

Regards,
Madhan

Reply all
Reply to author
Forward
0 new messages