handle urls with hash # with google analytics - google-analytics

I'm developing a js single-page web application using a javascript client side mvc (angular.js in this case)
I added google analytic to the site, but from what I could see so far (at least in realtime) google doesn't take into account the part of the uri after the hash
that is I have a url like mydomain.com.ar/#/ideas/1 but for google analytics it looks just like mydomain.com.ar/
any idea?

You need to parse the parameters after # and send the data by using _trackPageview in order to see them on your pages report.
and here is how to do it,
var params = {},
queryString = location.hash.substring(1),
regex = /([^&=]+)=([^&]*)/g,
m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
_gaq.push(['_trackPageview', queryString]);

Use $window dependency and call on route change.
Also use GA 'set' to ensure routes are picked up for Google realtime analytics.
$scope.$on('$routeChangeSuccess', function() {
$window.ga('set', 'page', $location.url());
$window.ga('send', 'pageview');
});

Related

Call a Google App Maker App with a parameter

Hello i am new here so if i ask a stupid question please forgive me.
We at AppAtSchool are working with Google ApMaker and we want to call a published App with 2 parameters. How can we read those in App Maker? Thanks in advance!
I'm guessing, that you are trying to read page URL parameters. In this case you can pass parameters like this:
https://script.google.com/<SomeMagic>/exec/?param1=value1&param2=value2#PageName
And then read them in page onAttach event(https://developers.google.com/appmaker/ui/logic#events):
google.script.url.getLocation(function(location) {
var params = location.parameter;
var param1 = params.param1;
var param2 = params.param2;
// Use parameters...
});
Maybe you also will need a way to genarate such links with parameters:
Integration between different Google Appmaker Apps
you can call your application with url something like this: script.google.com/blablabla/#viewname/paramValue, and take param on client side and send it to server side.
If you pass parameters to your App Maker app through URL parameters, your app can read the parameters using the google.script.url.getLocation method:
google.script.url.getLocation(function(location) {
console.log(location.parameters);
console.log(location.hash);
});
Find more details in the documentation

Google Analytics Get Custom Dimension After Setting One

In Google Analytics, after setting a custom dimension via:
var tracker = ga.getAll()[0];
tracker.set('dimension1', 'myCustomValue');
tracker.send('pageview');
I'd like to then GET the custom dimension value for that user when a user navigates to another page, via something like:
var tracker = ga.getAll()[0];
var dimension1_value = tracker.get('dimension1'); // 'myCustomValue'
Is there a way to do this?
There is no way native to Google Analytics to do this. Values are not stored in cookies anymore and there is no backchannel to the analytics server, get after set only works on the same page.
But of course nothing stops you from setting your own cookie/session storage and store the value(s) there (but then you knew that).

Site search functionality not working for POST based form submissions

I have a search functionality set up in my website, which uses a third party extension retrieve the search results. The search terms are not passed as query parameters.
Below is my sample URL for my search results:
mysite.com/search/results/dGVzdA/
I cannot change the URL to pass the search terms as query parameters.
So I'm trying to send Async Tracking from the google analytics javascript :
<script>
var _gaq= _gaq || [];
_gaq.push(['_setAccount','UA-XXXXXXX-X']);
//Push search query into google analytics
if ({url_segment_1} == 'search' && {url_segment_2} == 'results')
_gaq.push(['trackPageview'],['/search/?q=test']);
else
_gap.push(['trackPageview']);
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
The javascript logic seems to be executing fine, I've tested it by placing alert options. So is there anything that I'm implementing incorrectly with respect to _gaq.push().
Could someone throw light on the same
A couple of errors:
It's _trackPageview, with an initial underscore.
The argument for _trackPageview needs to be inside the array, like:
_gaq.push(['_trackPageview','/search/?q=test']);
[edit] There's also typo: _gap.push should be _gaq.push

Can my code get the Google map API version number?

I am not using the v parm when I load the Google map API. Therefore I always get the "release" version of the API.
My app has an "About" feature and I would like to display the API version number.
Is there a way for me to get that value or would this be an enhancement request?
simply use: google.maps.version
http://jsfiddle.net/doktormolle/anN4U/
There was a way to get it from the filename of the script that loaded:
//*************************************************************
// API version from post on Google Maps API group by bratliff
var file,loop;
var tags=document.getElementsByTagName("SCRIPT");
// alert("tags="+tags.length);
for (loop=0;tags[loop];loop++)
{
if (file=tags[loop].src.match(/http:\/\/[^\&\?]+\.google\.[^\&\?]+\/([0-9]+)\/[^\&\?]+\/main\.js/)) {
//alert(file[1]);
document.getElementById("apiv").innerHTML = "API v2."+file[1];
}
}
//*************************************************************
You should be able to do the something similar for API v3.

Tracking email opens in Google Analytics

We have tracking in our emails to track clicks back to our site through Google Analytics. But is there a way to track opens? I would imagine I have to add a google tracking image to the email somewhere. Possibly javascript too?
As others have pointed out, you can't use Javascript in email. The actual tracking is done by a request for __utm.gif though and the Javascript just constructs the GET parameters.
Google supports non-Javascript uses of Google Analytics per their Mobile web docs:
http://code.google.com/mobile/analytics/docs/web/
They document the full list of parameters, but the only necessary parameters are:
Parameter Description
utmac Google Analytics account ID
utmn Random ID to prevent the browser from caching the returned image
utmp Relative path of the page to be tracked
utmr Complete referral URL
The reference that describes all of the parameters that the Google Analytics tracking GIF allows is here. Use it to build an <img> tag in your email that references the GA GIF.
According to this post, the minimum required fields are:
utmwv=4.3
utmn=<random#>&
utmhn=<hostname>&
utmhid=<random#>&
utmr=-&
utmp=<URL>&
utmac=UA-XXXX-1&
utmcc=_utma%3D<utma cookie>3B%2B_utmz%3D<utmz cookie>%3B
It sounds like you are using campaign tracking for GA but also want to know how many opens there were. This is possible to do with Google Analytics, since they track pageviews or events by use of pixel tracking as all (I think?) email tracking does. You cannot use javascript, however, since that will not execute in an email.
Using Google Analytics pixel tracking:
The easiest way would be to use browser developer tools such as Firebug for Firefox or Opera's Dragonfly to capture a utm.gif request and copy the URL. Modify the headers to suit your needs. You can count it either as an event or pageview. If you count it as an event it should look something like this:
http://www.google-analytics.com/__utm.gif?utmwv=4.8.6&utmn=1214284135&utmhn=www.yoursite.com&utmt=event&utme=email_open&utmcs=utf-8&utmul=en&utmje=1&utmfl=10.1%20r102&utmdt=email_title&utmhid={10-digit time code}&utmr=0&utmp=email_name&utmac=UA-{your account}
You can use this to understand what describes what in the headers.
I better post this to save everyone the trouble of trying to construct that monstrous UTM gif URL.
You can now use the new Measurement Protocol API to send a POST request and easily record events, page views, hits, or almost any other type of measurement. It's super easy!
POST /collect HTTP/1.1
Host: www.google-analytics.com
payload_data
For example, here's a code snippet to send an event in C# (using SSL endpoint):
public void SendEvent(string eventCategory = null, string eventAction = null, string eventLabel = null, int? eventValue = null)
{
using(var httpClient = new HttpClient() {BaseAddress = new Uri("https://ssl.google-analytics.com/")}) {
var payload = new Dictionary<string, string>();
// Required Data
payload.Add("v", "1"); // Version
payload.Add("tid", "UA-XXX"); // UA account
payload.Add("aip", "1"); // Anonymize IP
payload.Add("cid", Guid.NewGuid().ToString()); // ClientID
payload.Add("t", "event"); // Hit Type
// Optional Data
payload.Add("ni", "1"); // Non-interactive hit
// Event Data
if (eventCategory != null)
{
payload.Add("ec", eventCategory);
}
if (eventAction != null)
{
payload.Add("ea", eventAction);
}
if (eventLabel != null)
{
payload.Add("el", eventLabel);
}
if (eventValue != null)
{
payload.Add("ev", eventValue.Value.ToString(CultureInfo.InvariantCulture));
}
using (var postData = new FormUrlEncodedContent(payload))
{
var response = httpClient.PostAsync("collect?z=" + DateTime.Now.Ticks, postData).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception("Could not send event data to GA");
}
}
}
}
Way easier than the hack with the __utm gif.
Helpful Example
You can easily add this to emails by doing this:
In an email:
<img src="{url}/newsletter/track.gif?newsletterName=X" />
In your MVC site, for example, NewsletterController:
public ActionResult Track(string newsletterName) {
using(var ga = new AnalyticsFacade()) {
ga.TrackEmailOpen(newsletterName);
}
return Content("~/images/pixel.gif", "image/gif");
}
In your Global.asax or RouteConfig:
routes.MapRoute(
"newsletteropen",
"newsletter/track.gif",
new
{
controller = "Newsletter",
action = "Track"
});
BOOM, done, son. You can now track email opens using a much nicer API that's supported and documented.
Is your requirement is to track how many times an e-mail is open by given user. We have similar problem. We are using SMTP relay server and wanted to track how many times our marketing e-mails are open in addition to google-analytics which register an even only when someone clicks inside link to our site in e-mail.
This is our solution. It is based on making a REST call by overriding image element of html (our e-mails are html base)
where TRACKING is dynamically generated url which points to our REST service with tracking information about person to which e-mail was send. It is something like that
//def trackingURL = URLEncoder.encode("eventName=emailTracking&entityType=employee&entityRef=" + email.empGuid, "UTF-8");
trackingURL = baseUrl + "/tracking/create?" + trackingURL;
It will be something like "https://fiction.com:8080/marketplace/tracking/Create?eventName=email&entityType=Person&entityRef=56"
When when actual e-mail html is generated it, TRACKING will be replaced by
Important point is to return a response of type image and return a one pixel transparent image with REST response.
So i'll assume that the email contains a link to your Site. Certainly GA can record how often that link is clicked because clicking the link will open the page in turn causing the function *_trackPageview()* to be called, which is recorded by GA as a pageview.
So as long as that page has the standard GA page tag, no special configuration is required--either to the GA code in your web page markup or to the GA Browser. The only additional work you have to do is so that you can distinguish those page views from page views by visitors from another source.
To do that, you just need to tag this link. Unless you have your own system in place and it's working for you, i recommend using Google URL Builder to do this for you. Google URL Builder is just a web-form in which you enter descriptive terms for your marketing campaign: Campaign Source, Campaign Medium, Campaign Content, Campaign Name. Once you've entered values for each of these terms, as well as entered your Site's URL, Google will instantly generate a 'tagged link' for you (by concatenating the values to your Site's URL).
This URL generated by Google URL Builder is the link that would be placed in the text of your marketing email.

Resources