Implementing Sub-domain & Cross-domain Tracking A Complete Guide Prepared By techbythebay.com 1
Contents 1. Sub Domain & Cross Domain Tracking for GA (asynchronous) I. Standard HTML/JavaScript Implementation II. jquery based implementation III. Implementation via Google Tag Manager IV. Special Case - Cross Domain tracking for iframes & links opening in new window 2. Sub Domain & Cross Domain Tracking for UA (analytics.js) I. Standard HTML/JavaScript Implementation II. Implementation via Google Tag Manager III. Special Case - Cross Domain tracking for iframes & links opening in new window 2
In this e-book, we have covered most of the case scenarios and procedures for implementing sub/cross domain tracking in Google Analytics (GA). Since GA uses first party cookies for storing visitor and session information, they can be read only by the issuing domain (website). This is the reason why tracking across different domains in GA requires specific code level configurations to pass on the cookie information from one domain to the other. Although this article covers the implementation mechanism using JavaScript methods offered by the GA tracking libraries, it is highly recommended that you leverage Google Tag Manager s capabilities to abstract out these complexities without requiring any programming knowledge. 1. Sub Domain & Cross Domain Tracking for GA (asynchronous) I. Standard HTML/JavaScript Implementation Tracking across subdomains For maintaining session information when a user navigates across subdomains, all of which share a common top level domain (TLD), we need to call the _setdomainname() method immediately after the setting the account via _setaccount(). For example, take the case of multiple regional sub domains for abc.com which need to be tracked under a common web property ID (say UA-1234567-2) - en-us.abc.com - br.abc.com - as.abc.com On all pages of each of these domains, you would need to add the following code (the additional _setdomainname() method highlighted in red) <script> var _gaq = _gaq []; _gaq.push(['_setaccount', 'UA-1234567-2']); _gaq.push(['_setdomainname', 'abc.com']); _gaq.push(['_setallowlinker', true]); _gaq.push(['_trackpageview']); </script> Notice that the common TLD common to all these domains is 'abc.com' and this is the domain which needs to be passed to _setdomainname() as the argument. 3
Tracking across cross domains Step 1: Add _setallowlinker() For maintaining session information across cross domains and tracking them under a common tracking ID, we need to first call the _setallowlinker() to allow cookie data to be read from the URL parameter on the target domain and enable cross domain linking. The method needs to be invoked just before the '_trackpageview' call, as shown below (highlighted in red) <script> var _gaq = _gaq []; _gaq.push(['_setaccount', 'UA-12345-1']); _gaq.push(['_setdomainname', 'example.com']); _gaq.push(['_setallowlinker', true]); _gaq.push(['_trackpageview']); </script> Step 2: Add the _link() method to all anchor links serving as entry points between the cross domains For all anchor based links originating from one domain to another, the _link method needs to be bound to the link s onclick event handler. For example, take the case of a link on www.example.com pointing to www.example2.com Link on www.example.com : <a href="http://www.example2.com/index.html" >Click Here</a> Now, we need to add the _link() method to this link in order to pass all the GA cookie parameters to 'http://www.example2.com/index.html', as shown below (highlighted in red) <a href="http://www.example2.com/index.html" onclick="_gaq.push(['_link', 'http://www.example2.com/index.html']); return false;" >Click Here</a> Please note that the string parameter argument passed to the _link method holds the same value as that of the anchor tag s 'href' attribute. This logic needs to be applied to all links pointing from www.example.com to www.example2.com and vice versa. 4
Step 3: Add the _linkbypost() to all form submissions that resolve to a page on the cross domain For all forms that resolve to a cross domain page after submission, we need to bind the _linkbypost() method to the form s onsubmit event handler. For example, consider a form hosted on www.example.com which resolves to www.example2.com, post submission Form tag hosted on www.example.com: <form name="form1" method="post"> We would need to add the _linkbypost() method, as shown below <form name="form1" method="post" onsubmit="_linkbypost(this);"> Here, 'this' is a reference to the current form html object and will remain constant. Please note that this mechanism may not work in cases where the form validation is handled using non-native JavaScript form functionality. This would be evident when the form tag does not have an 'action' specified in its tag. In such specific cases, you will need to rely on the _getlinkerurl method to decorate the URL to which the form resolves to after onsubmit. You can follow the same procedure mentioned in a latter part of this post which covers how to implement Cross Domain tracking for iframes & links opening in new window. II. jquery based implementation For websites with a small number of pages, it is feasible to adjust all links with the _link method. However, for large sized websites, this is definitely not a viable option and an alternative would be to use a global jquery code instead of having to tag individual cross domain links & forms with _link() and _linkbypost() respectively Step 1: If you do not have a jquery library included on the page, please make sure to add the following external library on all pages of both the cross domains <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> Step 2: Again, consider the two domains to be example.com & example2.com on which you want to implement cross domain tracking functionality. 5
On Example.com: Add the _gaq.push(['_setallowlinker', true]); as mentioned above and then include the following jquery script after the jquery library include: <script type="text/javascript"> //<![CDATA[ $(document).ready(function() { // Add onclick _link to all <a> elements on page where href contains example2.com $("a[href*='example2.com']").click(function() { _gaq.push(['_link', this.href]); return false; }); // Add onsubmit _linkbypost to all <form> elements on page where action contains example2.com $("form[action*='example2.com']").attr("onsubmit","_gaq.push(['_linkbypost', this])"); }); //]]> </script> On Example2.com: Add the _gaq.push(['_setallowlinker', true]); as mentioned above and then include the following jquery script after the jquery library include: 6
<script type="text/javascript"> //<![CDATA[ $(document).ready(function() { // Add onclick _link to all <a> elements on page where href contains example.com $("a[href*='example.com']").click(function() { _gaq.push(['_link', this.href]); return false; }); // Add onsubmit _linkbypost to all <form> elements on page where action contains example.com $("form[action*='example.com']").attr("onsubmit","_gaq.push(['_linkbypost', this])"); }); //]]> </script> You can test this setup by inspecting the URL after clicking on any of the links or submitting any of the forms between the sites. You should notice a string of parameters appended to your URL containing the cookie data from your originating domain. Again note that this mechanism may not work in cases where the form validation is handled using non-native JavaScript form functionality since _linkbypost relies heavily on native usage of the form POST functionality. You ll need to follow the procedure explained in Cross Domain tracking for iframes & links opening in new window section to decorate the URL to which the form resolves to after onsubmit. III. Google Tag Manager (GTM) implementation Tracking across subdomains For tracking across subdomains under a common tracking ID via GTM, you just need to set the TLD in the 'Domain Name' field under 'Domain and Directories' for all Track Types under the 'Classic Google Analytics' Tag Type. Using the same example of multiple regional subdomains under abc.com, screenshot given below shows configuration equivalent to setting the TLD via _setdomainname() - 7
Tracking across cross domains Setting up cross domain tracking via GTM is relatively simple and involves adding a few additional decorate tags for achieving the functionality. Step 1: Enabling _setallowlinker() to true To enable _setallowlinker() and set it to true, you simply need to check the button option under 'Domains and Directories' for all Track Types under the 'Classic Google Analytics' Tag Type, as shown below Step 2: Create 'Decorate Link' and 'Decorate Form' which are available as prebuilt templates. These tags are used to replicate the functionality achieved by _link() & _linkbypost() respectively. 8
Prior to creating the decorate tags, we would need to first create the helper tags for listening to clicks and form submissions. The prebuilt events generated by these tags (gtm.linkclick & gtm.formsubmission) will then be used to conditionally trigger the decorate tags to emulate the functionalities of _link() & _linkbypost() respectively. Step 2.1: Adding a Link Click Listener Tag: Add a tag of type Event Listener > Link Click Listener. You can name it "Link Click Listener". Add a single firing rule of "All pages", as shown below 9
Step 2.2: Adding a Form Submit Listener Tag: Add a tag of type Event Listener > Form Submit Listener. You can name it "Form Listener". Add a single firing rule of "All pages". Submit Please note that the Form Submit Listener may, at times, lead to inadvertent breaking of forms in older versions of IE and you might need to deselect the 'Wait for Tags' option and check if it still works for your case. The technical nuances involved in such cases is beyond the scope of this post and I ll cover them in future posts. Step 2.3 Create Decorate Link Tag(s): Add a tag of type 'Classical Google Analytics' and select 'Track Type' as 'Decorate Link', check the 'Allow Linker' checkbox under 'Domains and Directories' 10
Now we need to create a firing rule for triggering this tag whenever a user clicks on the cross domain. For this, we rely on two macros {{event}} This should match gtm.linkclick which is an inbuilt event triggered whenever a user clicks on an anchor link. This event is initiated by the Link Click Listener Tag explained in Step 2.1 {{element url}} This should match anything containing the cross domain within part of its URL. For example, for decorating links pointing from example.com to example2.com, the value of this macro should match any string containing example2.com Screenshot below shows how to setup the page rule for the decorate link tag for tagging links pointing from example.com to example2.com - 11
Please note that you will need to create a separate decorate link tag for every possible combination of cross domain navigation via links. In our example where only two domains are involved (example.com & example2.com), you will need to create another decorate link tag for tagging links pointing from example2.com to example.com. The only change would be in the page rule where {{element url}} would need to match any string containing example.com instead of example2.com If there were 3 domains being tracked under the same GTM container (say example.com, example2.com & example3.com), you would need to create 6 decorate link tags for each of the following combinations of cross domain navigation via links 12
links pointing from example1.com to example2.com links pointing from example1.com to example3.com links pointing from example2.com to example1.com links pointing from example2.com to example3.com links pointing from example3.com to example1.com links pointing from example3.com to example2.com Alternative Option: {{cross domain}} Create a custom JavaScript macro named 'cross domain' and add the following code with the Custom JavaScript field - function() { } var domains = ['example.com', 'example2.com']; var linkhost = {{element}}.hostname ''; if (linkhost!= '' && linkhost!= document.domain) { } for (var i = 0; i < domains.length; i++) { } if (linkhost.indexof(domains[i]) >= 0) return true; return false; Please note you can enter any number of domains (separated by ',') and use this as the second condition in place of the {{element url}} macro. You would just need to set the condition such that {{cross domain}} equals true Step 2.4: Create a Decorate Form Tag(s) For creating a Decorate form tag for every combination of cross domain navigation via form submissions, follow the same process and just replace the page rule condition such that {{event}} equals gtm.formsubmit instead of gtm.linkclick 13
IV. Cross Domain tracking for iframes & links opening in new window For tracking iframes which are hosted on a different domain (cross domain) than its parent page, you will need to use the _getlinkerurl() method to transfer visitor and campaign cookies from one domain to another. For example, suppose you include a form in an iframe that is hosted on www.example2.com. In order to transfer visitor information from the parent page that hosts the iframe on www.example.com, you would use JavaScript to load the iframe and pass in the cookie information using the _getlinkerurl() method. _gaq.push(function() { var pagetracker = _gat._gettrackerbyname(); var iframe = document.getelementbyid('myiframe'); iframe.src = pagetracker._getlinkerurl('http://www.example2.com'); }); Please note that the above function must be invoked before the iframe has loaded. The iframe tag in this case will have the 'src' attribute of the following form after appending the GA cookie attribution parameters via _getlinkerurl() <iframe src="http://www.example2.com? utma=150192876.542617860.1410256834.1410256834. 14 (organic) utmcmd=organic utmctr=(not%20provided)& utmv=- & utmk=188295784" id="myiframe"></iframe> Please note that the linker parameter should be set to true by including _gaq.push(['_setallowlinker', true]); on both the iframe hosting (source) and destination page. In order to implement the above functionality via GTM, please refer http://www.knewledge.com/en/blog/2013/11/cross-domain-tracking-for-iframes-withgtm/ 14
2. Sub Domain & Cross Domain Tracking for UA (analytics.js) I. Standard HTML/JavaScript Implementation Tracking across subdomains In Universal Analytics, tracking across subdomains is simplified and you just need to add the parameter 'auto' while creating a new tracker, as shown below <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-12345678-1', 'auto'); ga('send', 'pageview'); </script> This code will automatically write cookies to the highest level domain possible when the auto parameter is used. Tracking across cross domains Analytics.js provides autolink plugin to automatically implement cross domain linking across all the links on a page. Say you have a website hosted on example.com and you have the following links pointing to the following destination domains that you want to track with cross domain tracking: example1.com test.example1.com/page2 test.example2.com?page4 To add cross domain linking to these 3 links you would use: 15
// Load the plugin. ga('require', 'linker'); // Define which domains to autolink. ga('linker:autolink', ['example1.com', 'example2.com']); Now, page s existing create method must be updated by setting the allowlinker configuration parameter to true, as shown below: ga('create', 'UA-XXXXXX-X', 'auto', { 'allowlinker': true }); II. GTM implementation To implement cross domain tracking using GTM for UA, simply follow the steps below which are equivalent to loading the autolink plugin and setting the cookie domain to automatically pick up the highest level domain - Step 1: Add a (or edit your existing) basic page tracking tag (i.e. Tag Type of Universal Analytics; Track Type of Page View). Step 2: Find the field More settings > Cookie Configuration > Cookie Domain and enter "auto" (no quotes). Step 3: Under More Settings > Cross Domain Tracking, set the Allow Linker drop down menu to True. Step 4: Find the field More settings > Cross Domain Tracking > Auto Link Domains and enter the list of domains for which you want to implement cross domain tracking (depending on whether these domains are being tracked under a single container) The screenshot shown below depicts the configuration of aforementioned steps - 16
III. Cross Domain tracking for iframes & links opening in new window Please refer https://developers.google.com/analytics/devguides/collection/analyticsjs/crossdomain#iframe for a detailed guide on implementing cross domain tracking for iframes while using the analytics.js (Universal Analytics) tracking library Ref https://support.google.com/tagmanager/answer/3561401?hl=en http://moz.com/ugc/google-analytics-cross-domain-tracking-made-easy-14596 https://developers.google.com/analytics/devguides/collection/gajs/gatrackingsite#tr ackingiframes 17
About Us: We are a rapidly growing digital marketing agency based in Bombay, India and we offer cutting-edge internet marketing, end-to-end tracking and web analytics services to a wide range of businesses in India and abroad. We have vast cumulative experience is working with a number of brands and helping them succeed online. We will help position you right where your potential customers are present and help you derive huge benefits from the resultant exposure your brand gains on the internet. Our Offering: 360 Internet Marketing & Tracking Search Engine Optimization (SEO) Social Media Marketing (SMM) Pay Per Click Marketing (PPC) Web Analytics & Tracking Website Design & Development Mobile App Development Contact Us today to know how we can help you grow your business online or mail us at contact@techbythebay.com Visit our website for more info techbythebay.com Thanks for downloading the e-book. We welcome your feedback & suggestions. 18