I'm trying to track pages using Google Analytics within a GWT application. I already check the following thread: Integrating Google Analytics into GWT application
I think that the solution:
public static native void recordAnalyticsHit(String pageName) /*-{
$wnd.pageTracker._trackPageview(pageName);}-*/;
only works using the synchronous GA script.
I'm trying with the following:
public native void trackHit (String pageName) /*-{
try {
$wnd._gaq.push (['_setAccount', 'UA-XXXXXX-XX']);
$wnd._gaq.push (['_setDomainName', '.mydomain.com']);
$wnd._gaq.push (['_trackPageview', pageName]);
} catch (err) {
alert('failure on gaq' + err);
}
}-*/;
And is not working for me.
Here are my page- and event-tracking functions:
public static native void trackEvent(String category, String action, String label) /*-{
$wnd._gaq.push(['_trackEvent', category, action, label]);
}-*/;
public static native void trackEvent(String category, String action, String label, int intArg) /*-{
$wnd._gaq.push(['_trackEvent', category, action, label, intArg]);
}-*/;
public static native void trackPageview(String url) /*-{
$wnd._gaq.push(['_trackPageview', url]);
}-*/;
I do the _setAccount stuff like normal in the host page (needs to execute before trackPageview() etc will work:
<!-- Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-FAKE1234-2']);
(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>
You don't need to use setAccount every time you post an event, only at the beginning. I don't bother with try{}catch{} stuff... I don't actually know JavaScript.
There is a new version of Google Analytics out which uses a new analytics.js script. It's the same process though, just add the script in your html header:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-YOUR_ACCOUNT-X', 'auto');
ga('send', 'pageview');
</script>
And then can call the new methods like so:
public static native void googleAnalyticsTrackPageView(String url) /*-{
$wnd.ga('send', 'pageview', url);
}-*/;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With