Related
I'm trying to implement Google Analytics on Single Page Application. I'm trying to use Autotrack to track the virtual page views. But, it's not working.
Code:
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXX-1', 'auto');
ga('require', 'urlChangeTracker', {
shouldTrackUrlChange: function(newPath, oldPath) {
newPath = newPath.split('?')[0];
oldPath = oldPath.split('?')[0];
return newPath != oldPath;
}
});
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
<script async src="https://cdnjs.cloudflare.com/ajax/libs/autotrack/0.6.4/autotrack.js"></script>
Quoting from related github issue:
"The urlChangeTracker plugin does not support tracking URL hash changes. This is mentioned in the overview section of the plugin documentation.
Since almost all browsers in use today support the History API, that's what you should be using when creating SPAs. Hash changes should only be used for in-page navigation to anchor links."
When I try to set the appVersion in google analytics, then my event tracking stops working. Specifically, I'm trying to include the app version with event tracking so I can know which version of the app caused an event.
I've tried setting the app version like this:
ga('set', 'appVersion', app.version);
I've tried like this:
ga('send',
'event',
eventCategory,
eventAction,
{'page': pageName, 'appVersion' : app.version });
And I've also tried the alternative syntax:
ga('send',
{'hitType' : 'event',
'eventCategory' : eventCategory,
'eventAction' : eventAction,
'page' : pageName,
'appVersion' : app.version});
If I include appVersion, then event tracking stops working. No events show in realtime and no show the next day in the Behavior/Events section. The PageViews still work though.
As requested in the comments, I am editing to add in my event tracking code. It's been through several variations while I tried solve this problem. Here's what it looks like currently.
var app = {
trackEvent: function (pageName, eventCategory, eventAction, optionalEventLabel, optionalEventValue) {
var eventObject = {
'eventCategory' : eventCategory,
'eventAction' : eventAction,
'optionalEventLabel' : optionalEventLabel,
'optionalEventValue' : optionalEventValue,
'page' : pageName,
};
console.log("app.trackEvent - " + JSON.stringify(eventObject));
ga('send', 'event', eventObject);
}
}
I call this method from many places using a call like:
app.trackEvent("PageNameValue", "EventCategoryValue", "EventActionValue", "EventLabelValueIfIHaveOne", AnIntegerValueIfIHaveOne);
Any help or suggestions will be greatly appreciated.
Edit...
I found the following bug report that seems to apply: https://code.google.com/p/analytics-issues/issues/detail?id=366
The bug reporter mentions solving this problem by setting up a custom dimension. I will give that a try.
This appears to be be a Google Analytics bug. See https://code.google.com/p/analytics-issues/issues/detail?id=366 for more information.
As suggested by the bug reporter, the workaround is to use a custom dimension that you define in the Admin / Custom Definitions / Custom Dimensions section of the Google Analytics console.
Click "New Custom Dimension"
Enter name ( I entered customAppVersion )
Choose scope ( I chose Hit )
Click Create
Google will then suggest code examples for you, like...
var dimensionValue = 'SOME_DIMENSION_VALUE';
ga('set', 'dimension1', dimensionValue);
The only thing in the code sample that you need to change is the value of 'dimensionValue'. So I ended up with the following code.
ga('create', 'UA-########-#', 'auto');
ga('set', 'checkProtocolTask', null); // Disable file protocol checking (so that GA will work on Android devices)
ga('set', 'dimension1', app.version);
ga('send', 'pageview');
After this, the custom dimension will be applied to each hit recorded by Google Analytics and you can use that custom dimension to filter your results in the Google Analytics console.
As per google
Since the appName field must be sent with all app hits, it's often
best to set that field on the tracker itself using the set command or,
alternatively, when the tracker is created:
ga('create', 'UA-XXXXX-Y', 'auto', {
'appName': 'myAppName'
});
// The `appName` field is now set on the tracker, so
// screenview hits don't need to include it.
ga('send', 'screenview', {appVersion: '1.2'});
// Sending multiple parameters
ga('send', 'screenview', {appName: 'com.company.app', appVersion: '1.2'});
More information here
It works if you set at least the "appName", it's a good practice to set "appName" and "appId" before to set "appVersion"
ga('set', 'appId', app.id);
ga('set', 'appName', app.id);
ga('set', 'appVersion', app.version);
I'm trying to use Google Analytics (web) with my polymer app (updating the tracker object in routing.html as per this GA SPA doc). I used the Polymer Starter Kit as a starting point. I'm not seeing any pageviews though, apart from / - what's the suggested way of tracking app usage?
routing.html
page('/topstories', function () {
app.route = 'topstories';
window.ga('set', 'page', '/topstories');
});
page('/about', function () {
app.route = 'about';
window.ga('set', 'page', '/about');
});
index.html
<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-xxxxxxxxx-1', 'auto');
ga('send', 'pageview');
</script>
In addition to setting the page value on the tracker, you also have to send the pageview hit to Google Analytics. In your route callback functions you'll need to add the line:
ga('send', 'pageview');
You could also write a function that does all this for you, so you don't have to repeat the set and send calls every time.
function updatePage(path) {
return function() {
app.route = path.slice(1);
ga('set', 'page', path);
ga('send', 'pageview');
}
}
The your page route declarations would look like this:
page('/topstories', updatePage('/topstories'));
page('/about', updatePage('/about'));
My solution takes advantage of the middleware-ish page.js handler:
// Routes
page('*', scrollToTop, closeDrawer, function(ctx, next) {
ga('set', 'page', ctx.path); // simply add
ga('send', 'pageview'); // these rows
next();
});
But this also fires as the / route is initialised, so to not double count visits, remove the final ga('send', 'pageview'); from your <script> block.
I have setup google analytics on a small 1 page application website with 3 sections. I have implemented page fields and tracker object. However, every page title in google analytics is coming across as "Contact" although I have designated page titles for each pageview as below:
ga('create', 'UA-50789730-1', 'auto');
ga('set', {
page: '/',
title: 'Home'
});
ga('set', {
page: '/#features',
title: 'Features'
});
ga('set', {
page: '/#download',
title: 'Download'
});
ga('set', {
page: '/#contact',
title: 'Contact'
});
ga('send', 'pageview', '/');
ga('send', 'pageview', '/#features');
ga('send', 'pageview', '/#download');
ga('send', 'pageview', '/#contact');
Am I doing something wrong here?
Thanks!
Whenever you call set you're overriding the previously set data. That's why "Contact" is all you're seeing for the title in the code shown above, since that set call overrides the previous two.
I'd recommend reading the analytics.js overview to get a better idea of how the underlying library works:
https://developers.google.com/analytics/devguides/collection/analyticsjs/
Then once you have a better understanding, you should read the guide on tracking single page applications, as there are some gotchas you should be aware of:
https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
I am having a bit of difficulty implementing google analytics to my rails 4 project. I included the tracking code to the bottom of my layouts file and have even tried to remove turbolinks as suggested here however i google is still unable to detect this tracking cookie. Any ideas ?
I set up Google Analytics a few days before..
1.) The Turbolink Workaround
With Turbolinks, the Google Analytics JavaScript library is not sufficient to record a page visit for every page update.
The workaround should be loaded on every page and it can be included as an application-wide asset (it will load before Turbolinks).
Add the file app/assets/javascripts/analytics.js.coffee to include the Turbolinks workaround:
app/assets/javascripts/analytics.js
// Coffee
$(document).on 'page:change', ->
if window._gaq?
_gaq.push ['_trackPageview']
else if window.pageTracker?
pageTracker._trackPageview()
// Javascript
$(document).on('page:change', function() {
if (window._gaq != null) {
return _gaq.push(['_trackPageview']);
} else if (window.pageTracker != null) {
return pageTracker._trackPageview();
}
});
2.) Create a Footer Partial
Just create a a Partial into app/views/layouts -> _footer.html.erb
Then Call your Partial on your application.html.erb -> <%= render 'layouts/footer' %>
Insert into your Footer the Analytics Track Code:
<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-XXXXXXX-XX', 'herokuapp.com');
ga('send', 'pageview');
</script>
You must replace UA-XXXXXXX-XX with your tracking ID, and herokuapp.com with your Domain if you have any.
Here is code without using coffeescript:
app/assets/javascripts/analytics.js
$(document).on('page:change', function() {
if (window._gaq != null) {
return _gaq.push(['_trackPageview']);
} else if (window.pageTracker != null) {
return pageTracker._trackPageview();
}
});
I used this gem and was very easy to set up. No extra .js file creation.
Rails 3 helpers to manage google analytics tracking. Mostly intended for small to medium websites.
Just install the gem:
gem 'google-analytics-rails', '1.1.0'
Then run:
bundle install
Finally, this goes # the production environment configuration:
Production only
config/environments/production.rb:
# replace this with your tracker code
GA.tracker = "UA-112233-4"
app/views/layout/application.html.erb, in the <head> tag :
<%= analytics_init if GoogleAnalytics.valid_tracker? %>
I saw results immediately after pushing to Heroku.
I removed Turbolinks, and used the RailsProjects script, provided here:
http://railsapps.github.io/rails-google-analytics.html
Worked for me no problems. It detected it, and after a little while I could see the real time users so I know it is working.
Edit: The script appears to support Turbolinks on or off which is great.
# If Turbolinks is supported, set up a callback to track pageviews on page:change.
# If it isn't supported, just track the pageview now.
if typeof Turbolinks isnt 'undefined' and Turbolinks.supported
document.addEventListener "page:change", (->
GoogleAnalytics.trackPageview()
), true
else
GoogleAnalytics.trackPageview()
I was facing some problem in adding the GA with turbolinks so I referred some blogs and answers on stackoverflow and wrote a small blog on this. Please refer to this link
http://tarungarg402.blogspot.in/2015/01/google-analyicts-wth-rails.html
I use this in my rails app. I just put this in my application.js.erb
// GA racking code
(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','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-<%= Rails.env.production? ? '1' : '2' %>', 'auto');
// I have 2 GA properties- one for debug and another for production
// accommodate Turbolinks and track page views
$(document).on('ready page:change', function() {
ga('send', 'pageview');
});