How to fetch the current session's utm parameters in Google Analytics - google-analytics

Let's say a user gets to one of my pages with all the utm data (utm_campaign, etc.). On the page they land, a session is created in Google Analytics with all this info.
Then, they browse my site and get to another page. On that page, the utm_campaign isn't in the query string anymore.
Is there a way I can fetch the utm_campaign data?
Please note I use Universal Analytics, so it's ga instead of _gaq.
UPDATE: In case anyone is wondering, this code doesn't work:
ga(function(tracker) {
alert(tracker.get('campaignName'));
alert(tracker.get('campaignSource'));
alert(tracker.get('campaignMedium'));
alert(tracker.get('campaignKeyword'));
alert(tracker.get('campaignContent'));
alert(tracker.get('campaignId'));
});

Related

Google analytics api Get the userID / ClientID

I want to get the usage data of my customer out of google analytics, to make some usability analysis with it. For this, I need something that I can determine, which event was done by which user. Is there a possibility in a google analytics api to get this two parts linked?
You could add a user ID as a custom dimension, you'd probably want to set the scope to user.
https://support.google.com/analytics/answer/2709828?hl=en
This would allow you to connect up which users performed which actions.
Of course you can! :) I have used it in a lot of projects.
https://developers.google.com/analytics/devguides/collection/analyticsjs/sending-hits
Example:
ga('send', {
hitType: 'event',
eventCategory: 'Video',
eventAction: 'play',
eventLabel: 'cats.mp4'
});
Since clientId has been made available through the API as ga:clientId you can use this value.
I would recommend using a custom User Id though - setting you own generated User Id in the script using the Universal Analytics User ID feature and in your backend db.
Also add the id to any link you send to your clients via email/sms/etc. that lands on your homepage to follow up on marketing performance.
You would need to have some javascript that grab the id and set it on the pageview. (like Linker, but adjusted for user id)
Note to anyone using the Universal Analytics User ID feature The values returned in ga:clientId is actually the userId Even more interessting. (As of time of writing) GA fails if you request clientId from a User ID view. So you should use a non-User ID view to get the User ID. :)

How do I pass a parameter from my site into google analytics?

Let's say I have a site and the user comes into it with a parameter:
http://example.com&url=blahblahblah
How do I go about passing along the url value from the parameter into Google Analytics?
1) User comes to the page with a url in the params
2) User clicks a download link with a ga tracking code attached to it which was generated from ga account like this:
http://example.com/download/param1=dkljdf&_ga=1.149898996.39207121.1424368466
You have to create a custom Dimension and a metric for that.
About custom Dimensions and metrics:
https://developers.google.com/analytics/devguides/platform/customdimsmets
After you have created a Dimension, you can add metrics to it by view, in example.
Follow the steps here for Universal Analytics:
https://developers.google.com/analytics/devguides/collection/analyticsjs/custom-dims-mets
Note that due to not have 10 point of reputation, I wrote the a "_" in http like "ht_tp"
BUT:
I think what you want to know is the number os visitors that clicks a download link in your site that comes from, lets say "blahblahblah" as web origin or other methods.
For that, you have the param utm_source that you can receive directly in the url.
So instead of ht_tp://example.com&url=origin you should receive ht_tp://example.com&utm_source=origin
In this way, you have no care about it. Analytics is going to take care for you so you can get a report of clicks by source.
Or, just use the referer in case all the incoming visitors are from webs:
ga('set', 'referrer', 'ht_tp://example.com');
And a final option, to use Events:
_gaq.push(['_trackEvent', 'ReferencedVisitors', jsVarWhereYouHaveTheOrigin]);

Universal Google Analytics virtual pageview location

Situation
On our site we implement virtual pageviews for ajax filters and page scrollings.
When user open Rent page on our site:
real url: "/rent"
send to GA:
ga("send", "pageview", {page: "/rent/"})
When user scroll to second page:
we change real url via js: "/rent/?page=2"
send to GA (we care only about main page):
ga("send", "pageview", {page: "/rent/"})
Or when user drills down:
we change real url via js: "/rent/appartment/?page=2"
send to GA (we care about path):
ga("send", "pageview", {page: "/rent/appartment"})
But we noticed that really GA code does not take current real url (window.location) each time we call ga, but uses first time location. So when user drill down GA code send:
GET collect?...&t=pageview&dl=http://example.com/rent&dp=/rent/appartment&...
....
Referrer: http://example.com/rent/appartment
Here dl parameter is location of our page (not really current location) and dp is a page parameter in ga call. Notice that referrer is ok.
We decided to provide ga with real location (like in referrer) and change code to:
ga("send", "pageview", {page: "/rent/appartment", location: "http://example.com/rent/appartment"})
Problem
From now on I was satisfied, but was not guys that uses GA to analyze Paid Search effectiveness: bounce rate raised drammaticaly (something like 20% to 70%).
Drilling to the problem I've noticed that GA "loses" user when we remove campaign parameters (utm...) and send location without them.
Questions
Should I care about real location in this situation? How does location affects pageviews? How can I workaround or solve this problem?
Additional information
Seems like the main problem is that we drop CPC parameters when we change location for GA:
landing page: /rent?utm_source=...&... (or gclid for Google)
scroll down to second page: /rent?page=2 - there are no CPC parameters.
Additional information here: https://support.google.com/analytics/answer/1714454?hl=en
But I'm still can't figure out an appropriate solution.
When you send a hit to GA with analytics.js, it's going to send the data it has stored on the tracker object that you created when you invoked ga('create', ...);. You can override those values by passing in an object (as you did), but if no overrides are specified, that tracker data is used.
When the tracker object is created it collects data about the current page (e.g. url, title, window size, etc) and stores that information. It does not recollect that info before you send hits. You have to update it if that data changes.
That means if you're updating the page information in an AJAX site and want analytics.js to "remember" that you've updated the page, you'll have to set it on the tracker. The advantage to setting it on the tracker is that if you send other hit types (e.g. events, social, exceptions), you won't have to specify those new values each time.
So, instead of doing:
ga("send", "pageview", {page: "/rent/appartment"})
Do this:
ga("set", {page: "/rent/appartment"});
ga("send", "pageview");
Now, if you send an event later, the event will be associated with the apartment page.
UPDATE: there is now an official guide for how to properly track single page applications with Google Analytics.

Can I manually tell google the gclid?

Here's the scenario: visitor 1 (V1) clicks on an ad and gets a gclid as part of their __utmz cookie. V1 passes the url to visitor 2 (V2) on another computer. V2 visits the page from the specified url and therefore does not get a gclid. V2 completes the conversion, but adwords does not record the conversion as there is no gclid for V2.
If I can track all the above with some confidence, can I send the gclid from V1 to google when V2 completes their conversion?
Can I overwrite the __utmz cookie or can I add any javascript prior to the adwords conversion tracking script?
If I understand correctly, what you are trying to do is to maintain the campaign information if the user that was exposed to the ad sends the link to someone else. This is a major problem with user tracking in general and I see couple of methods that could help you to circumvent that.
First, gclid is used for adwords tracking. Theoretically you can save it in a cookie and then push it as a parameter to every URL that V1 is visiting and this way to maintain the campaign information when she shares the URL. This is possible, but the downside is that the data will appear as a new session of V1, not a new visitor (V2). From Google documentation:
...User A then copies this URL (containing the auto-tagging parameter)
and posts it in another location such as a public discussion board
(forum) or a social network, or sends it in an email or chat window to
other recipients.
Next, User B clicks this link (containing the gclid value) and arrives
at your website. Even though User B has never been to the website
before, this user will have the first session attributed to the same
click id (gclid) value that was assigned to the original User A. In
this case, you see new sessions (caused by User B) from an old
campaign.
Unfortunately there is no workaround to this scenario at the moment.
(source: https://support.google.com/analytics/answer/4588454?hl=en)
The downside however is that you fix a solution only for Google Adwords, while you may have campaigns on different platforms and sites that do not employ the gclid, but for which you use the UTM parameters.
Another solution I've stumble upon in the past is this one: http://www.lunametrics.com/blog/2013/10/02/direct-monster-fix-dark-social/ This script adds a unique query string parameter to every URL. If this URL is shared, in your GA reports it will show data in a custom dimension that denotes the user that shared the URL (V1) and those that used that URL (V2). This way you can analyze the "power of sharing". The downside is that you don't see the conversion under the campaign in question on GA. Never tried this script, only read about it.
Finally, you can make your own cookie and store the campaign information there. Then, you can append it with a parameter to every page that V1 views on your site. If V1 shares it, the campaign information will pass with this parameter to V2. The downside is that you will not see the conversion under the campaign in question on GA, only the parameter. However, you can see in your conversions report how many of campaign-->referral conversions you had by looking at the URL that led to the conversions (in the Reverse Goal Path, for instance). In addition, you are able to track this way not only Adwords campaigns with referrals, but any campaign. Try this project: https://github.com/dm-guy/utm-alternative. This project will help you with creating your own campaign tracking, but not with pushing it to the URL.
I work on AdWords conversion tracking. Here's how I'd do it using AdWords Conversion Import...
If the GCLID is passed in the URL to V2, then the site can grab the GCLID for V2's visit and store it in a cookie (provided you craft some JS to do so).
Then, when the conversion occurs, you've got another bit of JS that collects the cookie and stores it somewhere along with the date/time of the conversion and the type of conversion (this type should match an equivalent conversion type that you've defined in your AdWords account).
Once you have this process in place, you can batch the conversion records up daily and import it into AdWords via the conversion import service (https://support.google.com/adwords/answer/2998031).
The gclid value pertains to Adwords and Adwords only. To give credit to the converting gclid, you need to send the _ga cookie value in the URL query as such:
foo.com?_ga=1.2.xxxxxxxx.xxxxxxxxx
The x's above represent the clientID and this value needs to be cookied using JS:
<script>
function() {
var coo = window.location.href.split("_ga=")[1].split('.');
var cid = coo[2]+"."+coo[3];
return cid;
}
</script>
Have this above the UA tracking code:
<script>
ga('create', 'UA-xxxxxx-xx', {'clientId' : '<?php echo implode(".",array_slice(explode(".", $_GET["_ga"]), -2, 2)); ?>'});
</script>
Remember you must return the _ga cookie value in the URL in order for it fire off on this page. What's clever is, if you can record to a database IP and the associated _ga cookie value, you can track a user across different browsers and/or devices PROVIDED they are using the same IP address.

tracking sign-ups with google analytics

our marketing consultant has asked me to help with configuring google analytics to setup Goal Tracking for User Signups... from what I've read this is accomplished by assigning the URL of the page the user is directed to after a successful signup to the Goal you are trying to track.
but what if the URL your user is directed to is a URL they regularly visit? e.g. after signing up they are directed to their profile page - which is the same page they visit every time they login. is there some way to configure a referer to go with the goal URL so that it is the pair of them that define the goal? e.g. user visits /profile and is referred by /signup.
further complication: what if after signup the user is directed to a different page depending on the user type? it would be nice to configure a single Goal with multiple URLs (but still using the referer restriction described above).
an alternative would be to use an event... if the server creates a user then it could signal the view to output the javascript code that generates the appropriate event.
or... is there a way for server-side code to send events to google analytics? is there an api?
If your users are directed to is a URL they regularly visit you can make a conditional statement for the goal occasion with a virtual pageview, have a look at this: http://services.google.com/analytics/breeze/en/et_vps/index.html
If after signup the user is directed to a different page depending on the user type, you can use regular expressions to set goal URL pattern, like this ^user./login./(type1|type2|type3)/$, look here for more info: http://services.google.com/analytics/breeze/en/regex_ga/index.html
I came across this question in google and believe I found a more appropriate answer.
Google Analytics now provide a service called Analytics Measurement Protocol.
This will allow you to send server-side requests to track your users activities in your analytics account.
To track a sign up event as mentioned in the question, the best way I can see would be to first create an event based goal in your account with the category set to 'users' and an action as 'sign_up' (you can optionally provide a label and value). Then in your code once a successful sign-up occurs (maybe when a user confirms their activation email link?), send a POST request to www.google-analytics.com/collect with the following payload:
v=1 // Version.
&tid=UA-XXXXX-Y // Tracking ID / Property ID.
&cid=555 // Anonymous Client ID.
&t=event // Event hit type
&ec=user // Event Category. Required.
&ea=sign_up // Event Action. Required.
&el=label // Event label.
&ev=1 // Event value.
A full list of the parameters and their meanings are defined here: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
You could use an event that is triggered when the user submits the sign-up form :
onsubmit="_gaq.push(['_trackEvent', 'Category','Action','Label','Value']);"
and use the Category / Action / Label data model in Google Analytics to pass whatever data you need to pass, for example :
onsubmit="_gaq.push(['_trackEvent', 'Sign-up','Premium','6-month',6]);"
You then have to configure this Goal in Google Analytics as an Event, which lets you choose which combination of each of the fields Category / Action / Label / Value you want to use.
Another option, maybe less maintenance-heavy, is to use a query-string to identify people that get back to the Profile page after having just signed up. So instead of sending them back to /user/profile after they sign up, you send them back to /user/profile/?sign-up=true.
You will then be able to track these pages as a URL goal in GA using a Regular expression like :
\?sign-up=true
I wrote a helper function for tracking GA events.
function trackGoogleAnalyticsEvent(category, action, label) {
try {
ga('send', 'event', category, action, label);
} catch (e) {
console.warn('Google analytics error: ' + e);
}
}
Usage:
trackGoogleAnalyticsEvent('Signup', 'Signup Success', 'Facebook');

Resources