How to track multiple websites moving to one domain with Google Analytics - google-analytics

I am managing multiple websites that will soon move to one domain with each respective market being contained in a sub-directory e.g www.example.com/uk/.
The current situation is that all markets have their own GA property. I was wondering what the implications would be in just leaving the current setup as is?
I imagine GA alerts will fire implying that GA tracking is 'missing' across the website. Or would it be recommended to set the cookiePath field for each respective in the analytics.js create command?
The requirement is that each market is to have their own GA property giving them more flexibility.

Make translation table
function getPropertyId(){
var propertyIDs = {
'uk' : 'UA-24574-1',
'de' : 'UA-32656-4',
'fi' : 'UA-54544-6'
};
var fallBackId = "UA-Falback";
var path = window.document.location.pathname.split("/");
if(path[1]){
var propID = propertyIDs[path[1]] ? propertyIDs[path[1]] : fallBackId;
return propID;
}
else {
return fallBackId;
}
}
Use it when setting Property ID
ga('create', getPropertyId() , 'auto');
Request URI
You can expect troubles with Request URI variable, because:
From comment:
#GKyle Imagine, your current URL is mycompany.uk/page.html and new URL will be mycompany.com/uk/page.html. In old setup will be Requested URI /page.html in new /uk/page.html. There will be inconsistency if you will do nothing. But if you set up a filter removing /uk, etc..
Wonderful regex: ^(/(uk|de|au|en)\b/?)(.*)
From here: RegExp - remove /en or /de from pathname string and return rest
Rewrite string is /$A3
Create Advanced Filter
And please, TEST IT BEFORE!
Result
You can smoothly change tracking from multiple domains under one main domain if you keep setting Property ID.
Keep in mind possible changes in certain reports, specially path based reports.

Related

How to remove PII from URL (GA4 w/ GTM)

PII (Personally Identifiable Information) should never be sent to Google Analytics, not only it breaches GA Terms of Use, but you also leaking sensitive user data. So how to remove PII from URL, such as query string params (email, userId, ...) or even from location path when using Google Tag Manager (GTM) and Google Analytics 4 (GA4)?
Let's assume you've got already set up GA4 property and GTM installed on your page.
So let's create new tag for GA4 configuration. As Measurement ID I use lookup table variable (it's perfect when you've got multiple environments like testing, staging, production - all those have separate Measurement ID, but uses same GTM install script), but you can just simply write your G-XXXXXXXXX Measurement ID here. Then expand Fields to Set section, add page_location as Field Name and click on lego button next to Value.
Click on + (plus button) in upper right corner to add new variable.
As a Variable Type choose Custom JavaScript. In upper left corner write name of your new variable, I used Redacted Page Location.
And now we are getting closer to how to remove PII. In Custom JavaScript section insert JS function which should return redacted URL. Mine function uses regular expressions to replace PII from URL with some redacted text. Parameters I wanted to redact from url path are IDs of company, project, epic, and task; and userId from query params.
function() {
var url = window.location.toString();
var filter = [
{
rx: /company\/\d+/g,
replacement: 'company/REDACTED_COMPANY_ID'
},
{
rx: /projects\/\d+/g,
replacement: 'projects/REDACTED_PROJECT_ID'
},
{
rx: /epics\/\d+/g,
replacement: 'epics/REDACTED_EPIC_ID'
},
{
rx: /tasks\/\d+/g,
replacement: 'tasks/REDACTED_TASK_ID'
},
{
rx: /userId=\d+/g,
replacement: 'userId=REDACTED_USER_ID'
},
];
filter.forEach(function(item) {
url = url.replace(item.rx, item.replacement);
});
return url;
}
Let's say the URL of my page is https://www.example.com/company/2247/projects/2114/epics/19258/tasks/19259?userId=1234567, this function redacts it to https://www.example.com/company/REDACTED_COMPANY_ID/projects/REDACTED_PROJECT_ID/epics/REDACTED_EPIC_ID/tasks/REDACTED_TASK_ID?userId=REDACTED_USER_ID.
Select newly added custom variable, it's name should be in Value field, and save your GA4 tag.
.
Now let's test it. Switch to Preview mode and open your web site. In GA head to Debug View of your GA4 property, wait for page_view to pop up in timeline (maybe you will have to reload you page again), click on it and expand page_location variable. You should see your redacted URL.
That's all, enjoy!

Google Optimize - create A/B test with dynamic URL

i'm from business and I would like to ask is it possible to create A/B test with dynamic part of URL?
API of backend application returns calculation ID for every visitor and its included on URL.
For example:
We have main URL www.example.pl and I want to create A/B test with redirect to dynamic URL:
www.example.com/calculation/(calculculation_id)
Is it possible?
If your goal is to redirect from https://www.example.com/product/laptop/12345
to https://www.example.com/product/laptop-test/12345 for each product and not for the product 12345.
Select test type redirect
Set up redirect rules for each variant
Customize your page targeting rules with "contains" or "starts with."
Customize your advanced redirection"
1.Set up redirect rules for each variant
Find in domain/path com/product
Replace with com/product-test
Add/modify query parameters/fragments (leave blank)
Original: https://www.example.com/product/laptop/12345
Redirect: https://www.example.com/product-test/laptop/12345 (see point 3.Customize your advanced redirection)
! Do not worry if you are entering the specific product 12345 this value seen by the system as variable xxxxx !
2.Customize your page targeting rules with "contains" or "starts with."
Modify the page targeting rules to ensure that we include any URL containing example.com/product.
3.Customize your advanced redirection.
In our example the text "com/product" is replaced with "com/product-test".
This is the site where you can find more information :
https://support.google.com/optimize/answer/6361119?hl=en
Yes, you can do that in different ways. I'd suggest using Feature Flags approach in your A/B test in order to have a flag to generated the dynamic next URL from the API.
I'll try to summarize in two steps that you should go:
Add a Javascript in the Optimize Visual Editor for. Example here. The idea is this script to add a new flag:
window.FeatureManager = window.FeatureManager || {};
window.FeatureManager.variant_1_to_change_the_url = true;
On your own script, look at this flag to call the backend API in order to get the calculated URL:
// in case of the variant 1
if (window.FeatureManager && window.FeatureManager.variant_1_to_change_the_url) {
// calls the API passing this flag to get the new URL
const redirectURL = fetch('my_endpoint', true/false); // true/false could be the variant verification
location.href = redirectURL; // this is a sample, you can change the URL however you want
} else {
// the original variation
}

How to remove _ga query string from URL

I have a multidomain website for which there is GA tracking. Recently we moved to Universal Analytics and noticed that whenever the domain is changed (from US to Korean/Japanese), a _ga=[random number] is appended to the URL
i.e. from
abc.com
when i click on the japanese site, the URL becomes
japanese.abc.com/?_ga=1.3892897.20937502.9237834
Why does this happen?
How can I remove the _ga part of the URL?
Appreciate your help.
This is needed for cross-domain-tracking (i.e. track people who cross domain boundaries as one visitor and not as one visitor per domain). If you want cross domain tracking you cannot remove this. The _ga - part is the client id which identifies a session and since it cannot be shared via cookies (which are domain specific) it has to be passed via the url when the domain changes.
Since somebody set your site up for cross domain tracking I guess you actually want this (it does not happen by default). The parameter is a necessary side effect of cross domain tracking with Universal Analytics. If you do want this look in the tracking code for any of the linker functions mentioned in the documentation and remove them.
Updated to answer the questions from the comment.
Is there no way to remove the _ga string and still have the cross
domain facility?
No, currently not. Browser vendors work on better ways of cross
domain communication so there might be something in the future, but
at the moment the parameter is the best way.
Also, what if some user randomly changes the _ga value and presses
enter? How will GA record that?
If the user happens to create a client id that has been used before
(highly unlikely) his visit would be attributed to another user.
Realistically Google Analytics will just record him as a new user.
Updated
For those who like to play I did a proof of concept for cross domain tracking without the _ga parameter. Something along those lines could be developed further, as-is it is not suitable for production use.
Update: David Vallejo has a Javascript solution where the _ga parameter is removed via the history API (so while it is still added it is for all intents and purposes invisible to the end user). This is a more elaborate version of Michael Hampton's answer below.
I'm using HTML5 history.replaceState() to hide the GA query string in the browser's address bar.
This requires me to construct a new URL having the _ga= value removed (you can do this in your favorite language) and then simply calling it.
This only alters the URL in the address bar (and in the browser's history). Google Analytics still gets the information passed in via the query string, so your tracking still works.
I do this in a Go html/template:
{{if .URL.RawQuery}}
<script>
window.history.replaceState({}, document.title, '{{.ReplacedURL}}');
</script>
{{end}}
I was asked to remove this tag after it started showing up when we split our website between two domain names. With Apache Rewrite Rules:
RewriteCond %{QUERY_STRING} _ga
RewriteRule ^(.*)$ $1? [R=301,NC,L]
This will remove the tag, but will not be able to pass the _ga params to Google Analytics.
If the user doesn't mind a short refresh, then adding this code to every page
<?php
list($url, $qs) = preg_split('/\?/',$_SERVER['REQUEST_URI']);
if (preg_match('/_ga=/', $qs) ) header( "refresh:1;url=${url}" );
?>
will refresh after a second, removing the query string, but allowing the Google Analytics action to take place. This means that by the time your user has bookmarked or copied your URL, the pesky _ga stuff has long gone.
The above code will throw away ANY query string. This version will just strip out the '_ga' argument.
$urlA = parse_url($_SERVER['REQUEST_URI']);
$qs = $urlA['query'];
if (preg_match('/_ga=/',$qs)) {
$url = $urlA['path'];
$newargs = array();
$QSA = preg_split('/\&/',$qs);
foreach ($QSA as $e) {
list($arg,$val) = preg_split('/\=/',$e);
if ($arg == '_ga') continue; # get rid of this one
$newargs[$arg] = $val;
}
$nqs = http_build_query($newargs);
header( "refresh:1;url=${url}?${nqs}" );
}
You can't stop Google from adding the tag, but you can tell Analytics to ignore it in your reports. Thanks to Russ Henneberry for this: http://blog.crazyegg.com/2013/03/29/remove-url-parameters-from-google-analytics-reports/
It was written before Universal was released, so the language is outdated - now you create a new "view" (rather than "profile"). Creating a new view ensures that you still have the raw data in your default view (just in case you ever need it), so it's really the best solution (keeping in mind that you can't ever apply new settings retroactively in G Ax). Good luck!
You can't remove the _ga parameter from the URL on the website...BUT you can use an Advanced filter in Google Analytics to remove the query parameter from the reports!
Like this:
1) Field A: Request URI
Pattern: ^(.+)\?_ga
2) Field B: not needed
3) Output To -> Constructor
Field: Request URI
Pattern: $A1
This filter that will strip off all query parameters when _ga is the first parameter shown. You can get a lot fancier with the regex, but this approach should work for most websites.
See this page: https://support.google.com/tagmanager/answer/6107124?hl=en
& search for "use hash as delimiter"
Setting this value to true allows you to pass the value through a hash tag instead of through a query parameter
Should fix it
One way to handle this is to use the history.replaceState Javascript function to remove the query string from the URL after the page is finished loading and Google Analytics has done its thing. However, if you remove it too soon, it'll affect GA functionality (one visitor will show as multiple visitors). I've found that the following Javascript (with a 3-second delay)
<script defer src="data:text/javascript,async function main() {await new Promise(r => setTimeout(r, 3000));window.history.replaceState({}, document.title, window.location.pathname);}main();"></script>
I used "window.location.pathname" for convenience so that you can use the same script on many pages. However, you can also do like this (for the top page of the site):
<script defer src="data:text/javascript,async function main() {await new Promise(r => setTimeout(r, 3000));window.history.replaceState({}, document.title, '/');}main();"></script>
Or for a sub-page:
<script defer src="data:text/javascript,async function main() {await new Promise(r => setTimeout(r, 3000));window.history.replaceState({}, document.title, '/something/something.html');}main();"></script>
I did the "data:text/javascript" thing instead of a true in-line script so I could apply "defer" to it, although this probably isn't necessary if you're using a sufficiently long delay value.
You can filter out all (or only include) "?_ga=" parameters in Google Analytics for reporting purposes. I would also highly recommend adding a canonical to the base URL -- or adding the parameters to Google Webmaster Tools -- to avoid duplicate content.

Changing the delimiter from ? to # for Cross Domain Tracking

Trying to do cross domain tracking of links to an commerce site (Volusion); currently produces an error because of the ? delimiter. I see I can
_gaq.push(['_setAllowAnchor', true]);
on the volusion cart site in order to enable seeing # as the delimiter instead.
I'm using the script provided by Luna Metrics xdomain.js which auto tags outgoing links for cross domain tracking. It’s not clear to me what to change in the xdomain.js code to use # instead of ? as the delimiter, or can I make this default change with also using
_gaq.push(['_setAllowAnchor', true]);
on the referring domain where the outbound link is coming from?
You need to use _gaq.push(['_setAllowAnchor', true]) and _gaq.push(['_setAllowLinker', true]) on both ends. In theory you just need them in the receiving end. But usually the receiving end can be both. User can be going from domain A to domain B or the other way around.
After that you'll need to modify the lunametrics script because it won't allow you to send cookies in the anchor as it is today. It has this feature hardcoded. These are the lines that you need to modify in the lunametrics script.
Find this line:
var fullUrl = tracker._getLinkerUrl(jQuery(link).attr('href'));
And modify to this:
var fullUrl = tracker._getLinkerUrl(jQuery(link).attr('href'), true);
Then find this line:
_gaq.push(['_link',jQuery(link).attr('href')]);
And modify to this:
_gaq.push(['_link',jQuery(link).attr('href'), true]);
Here are the reference on these functions:
http://code.google.com/apis/analytics/docs/gaJS/gaJSApiDomainDirectory.html

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