Load Google Analytics from tampermonkey - google-analytics

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.

Related

google analytics traffic increase drastically when using setTimeout() function for GTM, GA, GTAG & FB scripts

I am using this code to load the tracking scripts 3000 ms after page load to optimize page speed.
I have checked using the chrome extension tag assistance legacy by google plugin and no major issues are recorded other than Same web property ID is tracked twice on google analytics
<body onload="loadtracking()">
<script>
function loadtracking(){
loadgtm();
loadfbpixel();
loadga();
loadgtag();
}
</script>
<script>
function loadgtm() {
setTimeout(function(){
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-xxxxx');
// window.dataLayer = window.dataLayer || [];
}, 3000);
return true;
}
</script>
<script>
function loadfbpixel(){
setTimeout(function(){
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;t.defer=true;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', 'xxxxx');
fbq('init', 'xxxxx');
fbq('track', 'PageView');
fbq('track', 'CompleteRegistration', {
content_name: 'Sign up',
content_category: 'xxxxxx'
});
}, 3000);
}
</script>
<script>
function loadga(){
setTimeout(function(){
(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', 'xxxxx', 'auto');
ga('send', 'pageview');
ga('send', 'event', 'xxxxx', 'xxxxx', 'xxxxx');
}, 3000);
}
</script>
<script>
function loadgtag(){
setTimeout(function(){
scriptgtag = document.createElement('script');
scriptgtag.src = "https://www.googletagmanager.com/gtag/js?id=xxxxx";
scriptgtag.async = true;
document.body.append(scriptgtag)
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'xxxxx');
gtag('event', 'conversion', {'send_to': 'xxxx'});
}, 3000);
return true;
}
</script>
But the traffic on GA increased drastically once I implemented this code by x 15
increase in traffic
I cant seem to figure out the issue.
You're loading Google Analytics to the page more than once (potentially even more if you're also loading it through Google Tag Manager) and it's firing a pageview for each of those loads. Let's step through each of your <script> blocks.
<script>
function loadgtm() {
setTimeout(function(){
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-xxxxx');
// window.dataLayer = window.dataLayer || [];
}, 3000);
return true;
}
</script>
This starts by loading GTM to the page. In order that its own triggers properly work, it's typically advised that this run in the <head> tags of your page. It loads asynchronously and non-blocking so running it on your page would hardly impact perceived page speed.
If you have a GA tag installed within GTM, this accounts for at least one pageview.
<script>
function loadfbpixel(){
setTimeout(function(){
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;t.defer=true;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', 'xxxxx');
fbq('init', 'xxxxx');
fbq('track', 'PageView');
fbq('track', 'CompleteRegistration', {
content_name: 'Sign up',
content_category: 'xxxxxx'
});
}, 3000);
}
</script>
This simply loads the Facebook pixel, so we'll skip over it, except to say that I would instead advise loading this within GTM triggered at pageview.
<script>
function loadga(){
setTimeout(function(){
(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', 'xxxxx', 'auto');
ga('send', 'pageview');
ga('send', 'event', 'xxxxx', 'xxxxx', 'xxxxx');
}, 3000);
}
</script>
That brings us to the first of your explicit Google Analytics installs. Assuming you're not running something like this from within GTM, this sends a pageview and your event after your 3000ms timeout. Again, from an interest of minimizing page speed impact, you should use the built-in Google Analytics tag within GTM and augment it with the event you wish you fire (though I advise making the switch to GA4 before the collection cut-off next year).
<script>
function loadgtag(){
setTimeout(function(){
scriptgtag = document.createElement('script');
scriptgtag.src = "https://www.googletagmanager.com/gtag/js?id=xxxxx";
scriptgtag.async = true;
document.body.append(scriptgtag)
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'xxxxx');
gtag('event', 'conversion', {'send_to': 'xxxx'});
}, 3000);
return true;
}
</script>
This brings us to the Gtag loader, which is really just a means of loading a small GTM instance to your page that bundles the Google Analytics tag. This would account for your second pageview in GA. Since you have GTM installed to the page, you shouldn't be using this loader at all and should instead opt for the built-in GA tag within GTM.
Best case, you're double-counting pageviews. Worst case, you're counting 2x + however many GA pageview tags you're firing off within GTM.
My advice:
Install the Google Tag Manager function without the timeout as high within the <head> tags as you can as provided by their installation instructions.
Install your Facebook tag as an HTML script (drop your timeout function) and trigger to execute at Page View.
Install the built-in "Google Analytics: Universal Analytics" tag, configure accordingly and trigger to run at Page View.
Install the built-in "Google Analytics: GA4 Configuration" tag, configure accordingly and trigger to run at Page View. This will be used by other GA4 tags for the base configuration, but also fires a pageview event without need for a second event-specific tag for the same.

Google Goal conversion not working when I download pdf

Google Goal conversion not working when I download pdf.
Here I followed following steps:
<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','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXX', 'auto');
ga('send', 'pageview');
</script>
<a href="/wp-content/uploads/2017/03/SEO-ebook-Final.pdf" onClick="javascript:_gaq.push(['_trackPageview','/wp-content/uploads/2017/03/SEO-ebook-Final.pdf']);">Ok<a/ class='bold-uppercase'>
</html>
gaq.push us classic Google analytics code as in ga.js. Your Google Analytics snippet shows you are using analytics.js which is universal analytics.
So basically you are mixing things you shouldn't be.
<script>
/**
* Function that tracks a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label. Setting the transport method to 'beacon' lets the hit be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var trackOutboundLink = function(url) {
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function(){document.location = url;}
});
}
</script>
You'll also need to add (or modify) the onclick attribute to your links. Use this example as a model for your own links:
Check out example.com
code ripped from Track outbound links

Polymer - Track app usage with Google Analytics

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.

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! :)

Google analytics with rails 4

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

Resources