Currently in my website, I used HTML5's pushState() and popState in links to increase the speed. However, this doesn't really change the real URL and it looks like it will affect and mess up the Google Analytics's code. (doesn't show a url change) Is there a possible solution for this? Thanks,
If you are using the newer analytics.js API, Google's documentation requires the following code to trigger the event:
ga('send', 'pageview', '/some-page');
If you are using the older ga.js API, David Walsh suggests AJAX websites to use the _gaq.push method:
_gaq.push(['_trackPageview', '/some-page']);
I know it's old question but since this question is first result in Google about tracking pushState() in Google Analytics and all answers are wrong I decided to answer it.
In other answers they mentioned to use directly ga('send' ..... ) but this is wrong way to do it.
First you have to 'set' parameters and then use 'send' to track it.
If you want to update only url, use following code
// set new url
ga('set', 'page', '/new-page');
// send it for tracking
ga('send', 'pageview');
If you want to update url and title, add title parameter to it
// set new url and title
ga('set', {
page: '/new-page',
title: 'New Page'
});
// send it for tracking
ga('send', 'pageview');
Source Single Page Application Tracking - Web Tracking (analytics.js)
February 2018 Update - Global Site Tag (gtag.js)
Google Analytics has a new tracking code snippet, so the other answers might not work for gtag.
This is the default tracking code. It only runs once even though we try to run it each URL changes.
gtag('config', 'GA_TRACKING_ID');
But with a page_path parameter we can make GA run manually.
gtag('config', 'GA_TRACKING_ID', {'page_path': '/new-page.html'});
And we can make something like this.
var origin = window.location.protocol + '//' + window.location.host;
var pathname = window.location.href.substr(origin.length);
gtag('config', 'GA_TRACKING_ID', {'page_path': pathname});
Single page application tracking with gtag.js (Google documentation)
Recent answer (2017)
You can now use Google's autotrack.js, a script that enhances analytics.js.
It includes a plugin that automatically tracks URL changes for single page applications.
You just need to include the script and the following line in your html:
ga('require', 'urlChangeTracker');
2020 Update
If you are using Google Analytics 4 you don't need to push the event anymore IF you enabled the Page views option in the Enhanced measurement feature in Data Streams menu.
At the time of writing, here in September 2013,
Google Analytics has a new JavaScript API.
After you've included Google's new "analytics.js" asynchronous snippet, use the send pageview command to track pages:
ga('send','pageview');
After your pushState madness, use this send pageview command to track your asynchronous navigation. According to Google's Documentation on Page Tracking with Analytics.js, the send pageview command will magically read and track the new location given by pushState, as it will, in the moment the send pageview command is called, use the following values by default (though you can specify them):
var locationToTrack = window.location.protocol+'//'
+window.location.hostname
+window.location.pathname
+window.location.search;
var titleToTrack = document.title;
var pathToTrack = location.pathname+location.search;
Note, Google's standard analytics snippet includes an initial send pageview command.
Update:
I've implemented Google Analytics tracking on my website in the way above that I described -- however, it does not seem to be successfully tracking any of the pushState page views.
I'm going to try specifying the location, title, and page name explicitly on the send pageview command, and see if GA tracks properly.
I'll post back with the results, unless I forget.
Using ga('send', 'pageview') was not registering a pageview on GA.
The way that worked for me is:
window.ga.getAll()[0].set('page', location);
window.ga.getAll()[0].send('pageview');
I can use it after changing the url with history.pushState.
I also had problems with ga('send','pageview');, after using history.pushState.
The workaround was simply make the URL explicit.
ga('send','pageview','/my-url')
Related
I made the caching of my web app much more aggressive and essentially made it a single page web app.
Even though I thought I implemented Google Analytics correctly according to the documentation, I am getting lots of "not set" pages. So I am guessing something is wrong with my code.
Here's how I believe I send a pageview:
ga('send', {
hitType: 'pageview',
page: pagePath
});
Where pagePathcontains a synthetic page address.
What is wrong about this?
for the single page web application you should have to apply the GA where the change of Route or hash occurs.
And there you should have to include following line of code in without removing the previously written code on the one time loaded page:
window.ga('send', 'pageview', location.hash);
Try this:
ga('send', 'pageview', 'page path');
There is a alternative method using GTM , where you can easily (!!) set-up virtual pageviews, more info on this link
EDIT:
This is an example of one of my sites where i set the fields for a Virtual Pageview in GTM
for SPA Solution,
you could try this one
ga('set', 'page', '/new-page.html');
ga('send', 'pageview');
https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
I have new analytics.js on a new webpage. This webpage has to be linked analytically to the existing webpages, managed by other people.
They sent me a line of code to do it:
_gaq.push(['_link', $(this).attr('href')]);
This is the old version of the analytics. I understand, that the same thing in new analytics can be accomplished using:
ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);
To where on the second I should put '_link' and $(this).attr('href') parameters?
There is not much documentation on the Google website. I have enabled official linker plugin, but they say, that this is not enough.
Edit: Bit of js after loading analytics.js looks like this:
ga('create', 'UA-12312312-1', 'auto', {'allowLinker': true});
ga('require', 'linker');
ga('linker:autoLink', ['friendlydomain.com'] );
ga('set', {page: window.location.href});
ga('send', 'pageview');
Where UA-12312312-1 is their tracking id. I can see, that ga parameter is added to the links going towards friendlydomain.com
This line of code:
_gaq.push(['_link', $(this).attr('href')]);
is not for outbound link tracking, it's the linker for Cross Domain tracking (see the documentation for the old ga.js library).
To accomplish the same with analytics.js it would be best to use the autolink plugin. This appends the client id to outgoing links; the linked pages must have linking enabled in the configuration to receive the parameter from the url and set it as client id when the tracker is created. GA will then use the client id to merge the sessions on both domains into one.
This will work only if both pages run analytics.js. Also you need to set both domains in the referral exclusion list in the property settings.
analytics.js is fairly flexible, so it mostly depends on how you want to view the data on the GA site.
One possible solution would be...
ga('send', 'event', 'link', 'click', $(this).attr('href'));
Also, the docs are fairly comprehensive. You might consider re-reading them here: https://developers.google.com/analytics/devguides/collection/analyticsjs/events#event_fields
I am running Google charts embedded in my site and I need to be able to track user interactions with the charts via select events as documented here: https://developers.google.com/chart/interactive/docs/events?hl=en#the-select-event
Following the analytics.js documentation, I added the following code to the head of my chart Javascript code:
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'click');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
(I replaced the dummy ID with the property ID for the site I want to track)
When I ran this code both in a standalone script in a browser and as embedded in my Wordpress site, the relevant Google Analytics events dashboard reported getting no hits.
I don't have much experience with this API so I am sure I am missing something out. Could anyone tell me what this is? I would really a appreciate a working example where Google chart events can get picked up by GA.
All help appreciated.
Nick
First, there is not ga('send', 'click');. Valid interaction types are 'pageview', 'screenview', 'event', 'transaction', 'item', 'social', 'exception', 'timing' (and most of them require additional parameters).
Since you want to track events that are initiated by the user I suggest you place the tracking call in the event callbacks (after you have loaded the analytics script at the top of the page).
If you look at the example linked in the documentaion in your question:
// google.visualization.table exposes a 'page' event.
google.visualization.events.addListener(table, 'page', myPageEventHandler);
...
function myPageEventHandler(e) {
alert('The user is navigating to page ' + e['page']);
}
Then the response to the user interaction is handled in the myPageEventHandler function, the callback for that event. So you could do in that callback whatever change to the visualization is appropriate and then send e.g. an event tracking call:
function myPageEventHandler(e) {
alert('The user is navigating to page ' + e['page']);
ga('send','event','chartevent','click on chart');
}
I am developing a front-end only JavaScript web application (used technologies are HTML5, CSS and JavaScript). This application is injected into a mobile application, that takes my JS web app and displays it in a fancy way.
I would like to track user's activities in my app using Google Analytics, but the problem is that my JS application injected into the mobile app doesn't have a regular URL that is needed when using GA for websites / web apps, but it's also not a mobile application to try GA for mobile apps.. The result is a hybrid between mobile and web application and I can only edit my JS application.
I have made the following image to visualize my problem better.
Using jsconsole.com I can programatically access my app and also check its console even when it is uploaded in iPresent. There are no errors. If I alert the app's URL, I got file URI:
alert( $( location ).attr( 'href ') );
//returns file:///var/mobile/..../index.html
I have tried many solutions-wanna-be (i.e. this or this), none of them works. But I am a beginner at this field, just blindly attempting to solve this, so probably missed some important note. Cookies works fine in my apps in iPresent.
My last GA code I used:
<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');
if(window.localStorage) {
ga('create', 'UA-NUMBER-1', 'none', {
'storage': 'none'
, 'clientId': window.localStorage.getItem('ga_clientId')
});
ga(function(tracker) {
window.localStorage.setItem('ga_clientId', tracker.get('clientId'));
});
}
else {
ga('create', 'UA-NUMBER-1', 'none');
}
ga('send', 'pageview');
</script>
Is it possible to make GA work with this hybrid web application that doesn't have a regular URL, but file URI? If so, how?
Thank u!
I suggest you take a look at Analytics Measurement Protocol. It will allow you to track most, if not all, interactions that the Google Analtycis JavaScript does using HTTP requests to https://www.google-analytics.com/collect.
Here is a pure JavaScript example of how to make the request using GET:
var hit = 'https://www.google-analytics.com/collect?';
hit += 'v=1'; // Version.
// Be sure to update the tid, Tracking ID, with your Google Analytics Tracking ID.
hit += '&tid=UA-XXXXX-Y'; // Tracking ID / Property ID.
hit += '&cid=555'; // Anonymous Client ID.
hit += '&t=pageview'; // Pageview hit type.
hit += '&dh=mydemo.com'; // Document hostname.
hit += '&dp=/home'; // Page.
hit += '&dt=homepage'; // Title.
httpGetRequest(hit);
function httpGetRequest(theUrl)
{
var req = new XMLHttpRequest();
req.open("GET", theUrl, true);
req.send(null);
}
You should look at HTTP GET request in JavaScript? and Eloquent JavaScript Second Edition - Chapter 17 HTTP for more information about sending HTTP requests using JavaScript. If you have access to jQuery then you could also use jQuery.ajax().
Once your request has been made you can log in to your Google Analytics account and see the pageview within Reporting. You can either see it in your Real-Time >> Overview or in Behavior >> Site Content >> All Pages.
In the image above I went to Behavior >> Site Content >> All Pages, shown in red. Then I set my date range to October 21, 2015, shown in blue. The highlighted portion shows the Document hostname and Page that I set in the JavaScript hit variable. Note that I have a filter that updates the Page to also include the hostname so you might just see /home for your Page.
If you have any questions, just let me know.
I've a question related to the simple tracking functionalities of Google Analytics.
I've realized my website with reveal.js, so my site follows a step navigation
http://[mywebsite.nl]/#/cover
http://[mywebsite.nl]/#/welkom
http://[mywebsite.nl]/#/pagina1
http://[mywebsite.nl]/#/pagina2
and I setup google analytics to track statistics.
My tracking issue is that when I land on my http://[mywebsite.nl] and I'm redirected to http://[mywebsite.nl]/#/cover it happens that the same page is tracked twice.
Is there a way to remove the tracking of the / of the website?
Thanks
You can take a look at Google's analytics.js tutorial, it allows some customization:
https://developers.google.com/analytics/devguides/collection/analyticsjs/pages
Page - The page path and query string of the page (e.g. /homepage?id=10). This value must start with a / character.
GA is nice to use as is, it provides some valuable insights.
But it is generally more valuable to track not page views but user actions.
GA is about page views, but as soon as you really want to understand users behaviour you need to track actions. I would recommend to take a look at http://www.devmetrics.io or http://mixpanel.com analytics.
You specify event and its properties. That means that you have full control.
var pageName = document.location.pathname;
// custom pageName processing if you need
devmetrics.userEvent('page_load', [pageName]);
....
// inside button handler:
devmetrics.userEvent('button_click', [pageName]);
I wouldn't recommend stripping the hostname from your pageviews, that can cause other issues with data quality.
Ideally, you would use a 3xx redirect to redirect from your main page to /#/cover, or don't send a hit before your site redirects. If that's not possible, you could try using a filter to drop hits from the URL you don't want to be double-counted.
You might try Google Tag Assistant Recordings to validate that your flow works as expected.
It was easier than I thought, sometimes we tend to over complicate things..
This is the super easy answer I was looking for, it is necessary a small tune on the javascript 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','//www.google-analytics.com/analytics.js','ga');
if(window.location.pathname != '/'){
ga('create', 'UA-XXXXXXXXX', 'auto');
ga('send', 'pageview');
}
It is just necessary to check the window.location.pathname and call the analytics function only for the desired urls.