Google analytics with rails 4 - google-analytics

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');
});

Related

How can I insert a Google Analytics snippet into my Mediawiki wiki pages?

This is turning out to be much more challenging than I expected.
There is a Google Analytics Integration extension:
https://www.mediawiki.org/wiki/Extension:Google_Analytics_Integration
But for the Global Site Tag version of Google Analytics, it refers you to the HeadScript extension:
https://www.mediawiki.org/wiki/Extension:HeadScript
The problem here is the download link (http://downloads.jingames.net/mediawiki/HeadScript.zip) looks a bit dodgy and the documentation mentions a bug.
I've also reviewed this discussion on the Mediawiki site:
How can I add the code into the <head>?
But it's a lot of telling and not much showing.
The Google Analytics snippet looks like this:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'TRACKING_ID');
</script>
I would prefer to insert it by updating a setting in LocalSettings.php config file.
Thanks!
I found a way to insert the tag into LocalSettings.php using the $wgHooks setting as demonstrated here:
https://www.mediawiki.org/wiki/Topic:Uxv32na6lh6wd5rf
Just replace TRACKING_ID (in both spots) with your Analytics tracking ID and paste this at the bottom of LocalSettings.php:
$wgHooks['BeforePageDisplay'][] = function( OutputPage &$out, Skin &$skin ) {
$code = <<<HTML
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'TRACKING_ID');
</script>
HTML;
$out->addHeadItem( 'gtag-insert', $code );
return true;
};
This is a very old post but for anyone else who might happen upon this I have found a possible solution by combining other examples.
I have used Tom's code as an example and replace the corresponding variables within the google analytics extension.
Change the hook in googleAnalytics.hooks.php line 9.
Old:
...
public static function onSkinAfterBottomScripts( Skin $skin, &$text = '' ) {
...
New:
...
public static function onBeforePageDisplay( OutputPage &$out, Skin $skin ) {
...
Then replace all mentions of $text with $code, there are 5 of them on lines, 14, 24, 31, 54, and 59.
Then at the end of the parser function above the return true; insert the following code on line 61.
$out->addHeadItem( 'gtag-insert', $code );
Finally go into googleAnalytics.php line 52 (Bottom of file) and replace the hook call to use the new hook.
Old:
...
$wgHooks['SkinAfterBottomScripts'][] = 'GoogleAnalyticsHooks::onSkinAfterBottomScripts';
...
New:
...
$wgHooks['BeforePageDisplay'][] = 'GoogleAnalyticsHooks::onBeforePageDisplay';
...
If everything worked out you will see the googleAnalytics extension script in the head element as opposed to within the body. I am going to try and contact the creator/contributors of the extension and see if it can be change or ask why its not this way already.
There is a google analytics extension.
Alternatively, the script can be added to Mediawiki:Common.js using document.write to link to the url and your site's UA-xxxxxx-x:
// GOOGLE ANALYTICS (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-xxxxxx-x', 'auto'); ga('send', 'pageview');
// END GOOGLE ANALYTICS

Google Analytics for Single Page Application with # views

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

add Meteor DocHead => DocHead.loadScript with Flow-router-ssr.

Can't figure out how to add the analytics code using DocHead.loadScript . Documentation assume that you more or less already understand it.
Have been trying in component, Client etc. Manage to get DocHead.setTitle(title); etc to work without problem.
Where do i add this DocHead.loadScript to make it work?
var gaScript = 'https://www.google-analytics.com/analytics.js';
DocHead.loadScript(gaScript, function() {
// Google Analytics loaded
ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');
});
Github: https://github.com/kadirahq/meteor-dochead

Load Google Analytics from tampermonkey

I'm trying to place Google Analytics code inside a Tampermonkey userscript, however the code simply doesn't work as evidenced by:
The callback function for the pageview doesn't fire and
I don't show up as an "active user on site" in Real-Time view for Google Analytics
Here is the script, nice and simple (some values obfuscated):
// ==UserScript==
// #name GA Injector
// #namespace mynamespace
// #version 0.1
// #description Injects google analytic code for testing
// #match mywebpage
// #copyright 2014 me
// #require http://code.jquery.com/jquery-latest.js
// ==/UserScript==
Console.log('This part works okay');
(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', 'mytrackingcodeishere', 'auto');
ga('send', 'pageview', {
'hitCallback': function() {
console.log('Tracking worked okay!');
}
});
The script works fine when run in Chrome's javascript console, what is it about Tampermonkey or my configuration that prevents Google Analytics from being run?
Try simply injecting this entire code into the page scope, like this:
var script = document.createElement('script');
script.innerHTML = "..Your JS Code..";
document.body.appendChild(script);
If it does works when run from console, it will this way.

Google Analytics Goals not getting tracked

I realize that there's a plenty of questions about not working GA goal tracking. I did my homework and read lots of them before posting my question.
Here's my issue... This is the documentation that I used to create my code: https://developers.google.com/analytics/devguides/collection/analyticsjs/events
I am using the analytics.js version
<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-xxxxxxxxxxx-x', 'mywebsite.com');
ga('send', 'pageview');
</script>
I tried to implement the code via both pure javascript and jQuery but neither seems to work.
Here's my code:
link to be tracked:
Get In Touch Today
jQuery approach:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#cta-footer-btn').on('click', function() {
ga('send', 'event', 'CTA_footer', 'contact_footer');
});
});
</script>
I also tried the pure js approach suggested:
<script>
var downloadLink = document.getElementById('cta-footer-btn');
addListener(downloadLink, 'click', function() {
ga('send', 'event', 'CTA_footer', 'contact_footer');
});
/**
* Utility to wrap the different behaviors between W3C-compliant browsers
* and IE when adding event handlers.
*
* #param {Object} element Object on which to attach the event listener.
* #param {string} type A string representing the event type to listen for
* (e.g. load, click, etc.).
* #param {function()} callback The function that receives the notification.
*/
function addListener(element, type, callback) {
if (element.addEventListener) element.addEventListener(type, callback);
else if (element.attachEvent) element.attachEvent('on' + type, callback);
}
</script>
Neither seems to be tracking the link clicks.
Any thoughts or suggestions why this is not working will be greatly appreciated.
Thanks!
Make sure you have the analytics tracking code inserted in the head section of the document (not necessary, but makes sure that the required library is fully loaded along with the ga object before making any references to ga() functions), and also make sure jQuery is also loaded before being used. You can use the console (usually F12 in browsers) to check for any error being thrown. These are are general steps to verify if you have tracking installed properly.
It might take a while before data starts showing up in reports if you have just installed, so don't worry. You can install the GADebug extension for Chrome to check if tracking beacons are sent properly.
Also, you can use the click() function from jQuery. It works fine for me.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#cta-footer-btn').click( function() {
ga('send', 'event', 'CTA_footer', 'contact_footer');
});
});
</script>
Hope that helps! :)

Resources