I am trying to implement Google analytics with rails 5. Since i wanted to keep my turbolinks, i am following http://railsapps.github.io/rails-google-analytics.html this method. Added app/assets/javascripts/google_analytics.js.coffee:
class #GoogleAnalytics
#load: ->
# Google Analytics depends on a global _gaq array. window is the global
scope.
window._gaq = []
window._gaq.push ["_setAccount", GoogleAnalytics.analyticsId()]
# Create a script element and insert it in the DOM
ga = document.createElement("script")
ga.type = "text/javascript"
ga.async = true
ga.src = ((if "https:" is document.location.protocol then
"https://ssl" else "http://www")) + ".google-analytics.com/ga.js"
firstScript = document.getElementsByTagName("script")[0]
firstScript.parentNode.insertBefore ga, firstScript
# 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()
#trackPageview: (url) ->
unless GoogleAnalytics.isLocalRequest()
if url
window._gaq.push ["_trackPageview", url]
else
window._gaq.push ["_trackPageview"]
window._gaq.push ["_trackPageLoadTime"]
#isLocalRequest: ->
GoogleAnalytics.documentDomainIncludes "local"
#documentDomainIncludes: (str) ->
document.domain.indexOf(str) isnt -1
#analyticsId: ->
# your google analytics ID(s) here...
'UA-XXXXXXX-XX'
GoogleAnalytics.load()
This doesnt work. I tried to debug it using Google analytics debugger.but its only showing
_gaq.push processing "_setAccount" for args: "[UA-XXXXXXX-XX]":
this in the console. When i tried calling directly
GoogleAnalytics.trackPageview()
I am getting data in my analytics account.
But throwing this
Method _trackPageLoadTime is deprecated. _trackPageLoadTime is deprecated. Site Speed tracking is enabled by default with trackPageview call at 1% sampling. Use _setSiteSpeedSampleRate for changing sample rate.
error in my console.
What is the issue? Please help.
The article you are referring to is quite old (in Rails Land). Did you try
https://gist.github.com/esBeee/545653241530f8f2c2e16371bec56f20
?
In application.html.erb:
<script type="text/javascript">
(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-XXXXXXXX-X', 'auto');
</script>
<% end %>
Put this file into your assets/javascripts/ folder and assure it gets loaded by checking or editing your assets/javascripts/application.js file as appropriate
document.addEventListener 'turbolinks:load', (event) ->
if typeof ga is 'function'
ga('set', 'location', event.data.url)
ga('send', 'pageview')
I tried the following on Rails 6 with Turbolinks and Webpacker and it works, I hope it helps someone.
Add this to the layout file's head:
<script async src="https://www.googletagmanager.com/gtag/js?id=YY-XXXXXXXXX-Z"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
</script>
And then add this to your application.js file:
$(document).on("turbolinks:load", function() {
gtag('config', 'YY-XXXXXXXXX-Z', {'page_location': event.data.url});
})
Replace YY-XXXXXXXXX-Z with your own tag and you are done.
Related
I want to create a smiliar snippet to Google Analytics and Intercom:
Intercom example https://developers.intercom.com/installing-intercom/docs/basic-javascript
//Set your APP_ID
var APP_ID = "APP_ID";
window.intercomSettings = {
app_id: APP_ID
};
(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',w.intercomSettings);}else{var d=document;var i=function(){i.c(arguments);};i.q=[];i.c=function(args){i.q.push(args);};w.Intercom=i;var l=function(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/' + APP_ID;var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);};if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})();
or Google Analytics:
Adding analytics.js to Your Site
The analytics.js library is a JavaScript library for measuring how users interact with your website. This document explains how to add analytics.js to your site.
The JavaScript measurement snippet
Adding the following code (known as the "JavaScript measurement snippet") to your site's templates is the easiest way to get started using analytics.js.
The code should be added near the top of the <head> tag and before any other script or CSS tags, and the string 'GA_MEASUREMENT_ID' should be replaced with the property ID (also called the "measurement ID") of the Google Analytics property you wish to work with.
Tip: If you do not know your property ID, you can use the Account Explorer to find it.
<!-- Google Analytics -->
<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-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
Which design patterns did Intercom and Google use to create this snippets? How are they working internally? Can you give me maybe a basic structure so I can fill it with the functionalites I want?
The IIFE of google analytics ( adn Intercom ) are basically just the shortest way they could write a script loader that will work for all browsers.
If we write the shorthand fully, the structure becomes easier to read:
window.GoogleAnalyticsObject = 'ga';
window.ga = window.ga || function() {
window.ga.q = window.ga.q || [];
window.ga.q.push( arguments );
},
window.ga.l = 1 * new Date();
var a = document.createElement( 'script' );
var m = document.getElementsByTagName( 'script' );
a.async = true;
a.src = 'https://www.google-analytics.com/analytics.js';
m.parenNode.insertBefore( a, m );
window.ga('create', 'UA-XXXXX-Y', 'auto');
window.ga('send', 'pageview');
The Intercom example basically does the same.
So this script guarantees first that the proper names exist on the window object. If the google analytics object already existed, it will be used, else it'll become that function that will save the data in an array. This prevents the script to be added multiple times, so if another plugin also tries to load the same script, they will share their GA instance.
Then the script creates a new script tag and configures it to the url of the actual google analytics script. Once the newly created script tags gets added to the page, it will load the actual analytics.js script.
Although I haven't looked at the fine details of the analytics.js, but i'm pretty sure it'll then unpack or merge the window.ga object we created and replace it with the actual analytics script.
So all in all, this is a fancy way to write <script src="https://www.google-analytics.com/analytics.js"> that will work on old browsers and will make sure we do not have multiple instances of the script fighting eachother if multiples are loaded on a single page.
The actual inner workings of the analytics.js script and the intercom widget script are not included in these loader scripts, so I'm not going to go into detail how those work, that should be a different question showing the lines of code of the actual analytics.js script.
Edit:
window.ga = window.ga || function() {
this line makes sure that window.ga is a function.
For simplicity, let's consider it's a page where ga does not exist yet.
So when we call ga('create', 'UA-XXXXX-Y', 'auto'); and ga('send', 'pageview'); we run the following statements:
window.ga.q = window.ga.q || [];
window.ga.q.push( arguments );
window.ga.q = window.ga.q || []; makes sure that window.ga.q is an array.
And then window.ga.q.push( arguments ); pushes the arguments to it.
So calling ga('create', 'UA-XXXXX-Y', 'auto'); and ga('send', 'pageview'); before the analytics script is loaded results in the following:
window.ga.q = [
[ 'create', 'UA-XXXXX-Y', 'auto' ],
[ 'send', 'pageview' ]
];
Remember, window.ga is a function, but function are also kind of objects in javascript. So we can add the property q to the function just the same as if window.ga was an object and the function will still work.
Once the analytics script gets loaded, it will look at the window.ga.q array and run all those commands.
The problem is, look at the analytics.js script. It's also written in the same style, so it'll take hours to rewrite it with all the shorthands replaced, so i woudl try to look for like the annotated non-minified source of that script if it's available somewhere.
I have google analytics account, i have added analytics code in my index.html. But Mycampaign tag in google analytics is not showing any data. I have user google URL builder to generate campaign url. What could be the problem?
1. UTM tags disappeared on landing page of website
2. analytics code may have some changes
here is the analytic code added in index.html, i am using UA(Universal analytics)
<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-xxxxxxx-x', 'auto');
ga('send', 'pageview');
</script>
If you're executing this on localmachine or in a Web with no domain this can be a problem, the Google Analytics Universal das dependencies with the domain (sometimes this no happens but well), so you can try to change the
ga('create','UA-1-1','auto');
for
ga('create', 'UA-XXXX-Y', {
'cookieDomain': 'none'
});
or look for other options on this thread:
Can you test google analytics on a localhost address?
Warn us if this help your issue
Might help if you posted the tagged URL. I know you used the URL builder but it still could be incorrect. Also, if you're looking at a filtered view in Analytics you won't see all traffic. Check that the tag is firing using Google Tag Assistant.
If you could provide an example page that has this issue, it would be helpful. Then we can look closely at your UTM parameters and also you GA javascript.
I inserted Google Analytics with the following code snipped.
<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-xyz-1', 'xyz.com');
ga('send', 'pageview');
</script>
Now I want to track a specific page in my ajax application. The following link
describes how to push events to google analytics:
https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
If I try to execute the following command, I just get the error saying "_gaq" is not defined.
_gaq.push(['_trackPageview', 'myPage']);
Am I doing something wrong here or are the docs are outdated?
Edit: So there seems to be a new API. What would be the equivalent to:
_gaq.push(['_trackPageview', 'myPage']);
Would this be the same command in the new API?
ga('send', 'pageview', 'myPage);
You're mixing the new analytics.js with the old async ga.js. Use analytics.js (Universal Analytics) event tracking documentation instead.
This is actually the code that samples the variable is not defined _gaq, reviewing the Analitycs page I see that the code is as follows:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
(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);
})();
Check the block of code and make sure that all is well implemented
Jan, I believe the pageview request is already in the snippet you mentioned:
ga('send', 'pageview');
Just make sure you the line above this -- you need to make sure that domain and Analytics account ID is specified:
ga('create', 'UA-123456-1', 'yourdomain.com');
Looking at your code, it seems that you are using new Universal Analytics library, so _gaq.push commands won't work anymore. When you refer to documentation, always double check you looking at Analytics.js section (link).
I've gotten a lot of response saying that my Google tracking code was excessive in many ways, and I suspect that perhaps not all features are working. (There's certain metrics that aren't showing data: "Paid Traffic" and "Campaigns" for example)
Is it possible that Google is rendering less than useful tracking codes?
Should I return to the old format of tracking codes, since I know that they work well?
Could it be the placement on my page? Google recommends before </head> yet everyone on here recommends before </body>.
What Google rendered for me: (Current)
<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-40498113-1', 'caseykidd.com');
ga('send', 'pageview');
</script>
My old Tracking Code: (Circa One Year Ago)
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-28036048-1']);
_gaq.push(['_trackPageview']);
(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>
The "new" tracking code is analytics.js, which "is part of Universal Analytics, which is currently in public beta".
Granted you can probably get the Google Analytics pages to give you the beta code, I would probably stick with the tried and true ga.js on production websites until Google pulls it out of beta.
The new tracking code has async enabled by default, so in most recent browsers it won't stall the page load even if there is a problem loading Google Analytics. That is why they recommend you put the ga.js tracking code before </body> instead of </head>.
I recently installed my analytics code, but it has been saying for a while that it's not installed.
I can't think of a better place to put it. Does the script interfere with my other script (for the fade-in)?
Also, should my script be the first thing I include? (maybe after </title>?)
Hits are showing under "real-time" but not as actual visits. The tracking info still says "tracking not installed." I refreshed to make sure.
UPDATE: Google is showing my hits, and I have data... but it says that tracking is not installed. I've had this issue with Wordpress sites, but they were remedied with the use of a plug-in.
Should I try using the old tracking script? I know that one works.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Casey</title>
<meta name="description" content="" />
<meta name="keywords" content="">
<link href="home.css" rel="stylesheet" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
if (window.localStorage && !localStorage['faded']) {
localStorage['faded'] = true;
$('body').hide().fadeIn(500);
}
});
</script>
<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-40498113-1', 'caseykidd.com');
ga('send', 'pageview');
</script>
</head>
The only thing I see that's "off" is
ga('create', 'UA-40498113-1', 'caseykidd.com');
should be
ga('create', 'UA-40498113-1', {'cookieDomain':'caseykidd.com'});
But I don't think that's really the problem (I think GA is just ignoring how you did it and it happily works out okay, based on your lack of subdomain in the URL). edit: oddly, the generated code within the GA interface looks like what you have, but that's not what the documentation shows. I have verified that this is apparently an undocumented syntax shortcut for setting the cookie domain.
You said you see the data in the "real time" reports so I assume your account number is correct.
My only suggestion is to wait a while for the data to show up. GA's "real time" stuff only shows some basic info. Stuff like "visit" may not be immediately available because of the nature of the dimension/metric. For example, GA (and most other tracking tools) usually don't count it as a visit until the visit is actually over. So if you went to your site to test it and then immediately went to GA to check...well the visit isn't actually over until 30 minutes after the last request to GA.
update (additional info based on your comment below and update to your question)
I don't necessarily think you need to use the old tracking script.. I don't know how it works within Google's system, but Google actually officially states that it can take up to 24 hours for everything to be completely recorded.
Also to be fair, Universal Analytics (analytics.js) is open beta phase at the moment.. it could be that they haven't gotten around to updating that verification logic, or there could be a bug in it, or it could be one of the things that take closer to 24 hours to be updated.
Again, since you are seeing data, I don't think you are doing it wrong, but for sh*ts and grins you can read the entry on verifying your web tracking setup. Are you testing on some other domain than what the web property is setup for? I think GA may not report that implementation has been verified if it has not received a request from the domain specified in the property settings. Also the the manual says it must be on the "homepage" of your site. Are you testing on the homepage or using a custom page name?
As a test I setup analytics.js code in a new web property for a domain that did not previously have any GA tracking on it, when I posted this answer. I see my data but the tracking status remains as "not installed." It has not been 24 hours for me yet, but I personally don't really care, as long as the data is coming in. Even Google's troubleshooting document entry for tracking verification just says to look at the request and verify data in the reports, so that's good enough for me.
But if it really bothers you that much, and you've waited at least 24 hours, I would suggest posting a possible bug report on the google support forums.
update 2: It's been about 18 hours, since I last checked, and the status msg has changed to "receiving data" on my test domain/web property.
When you create a Google Analytics account you're provided with the tracker script, which in my experience has always been the below:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
_gaq.push(['_trackPageview']);
(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>
That uses the _gaq object, where basically you fill an array of arrays with stuff you want Google Analytics to do later, and when it loads it looks for _gaq, reads the array and executes those commands. It then replaces _gaq with an object that immediately responds to calls to .push() by executing the commands described in the array.
So for example if you added this to the array:
_gaq.push(['_trackEvent', 'Ordering', 'Clicked', 'Order Now top-left']);
Then one of 2 things would happen:
If GA hadn't loaded yet, this array would be added to the _gaq array, waiting for GA to finish loading. When GA did load it would read this and fire the trackEvent command with the parameters you included.
If GA had already loaded, then this call to .push() would cause the trackEvent command to be executed immediately, with the parameters you included.
By the way I usually simplify the example script to:
<script>
var _gaq = [
['_setAccount', 'UA-XXXXXXXX-1'],
['_trackPageview']];
(function() {
var ga = document.createElement('script'); 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>