How-To Google Analytics with Typo3

Written by NickWal

Google Analytics is an increasingly popular web analytics tool, providing high quality information about visitors to your site, such as how they found you (links, search keywords and so on), where they are from (down to the city in some cases) and which pages they visited and how long they staid on your site. It differs from log analysis (the processing of logs generated by your web server) in that you must have a copy of the Google Analytics Javascript on every page you want analyzed. The Javascript needs to be placed at the very end of your page, just before the closing body tag. With Typo3, this is extremely easy to do, regardless of whether you are using pure TypoScript templates or templates that use HTML, thanks to the ‘wrap‘ property and cascading templates. Below is an example:

After the last line of TypoScript in the Setup section of the web site root template, place code like this:

page.wrap (   
 | <script type="text/javascript">  
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");  
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));  
</script>  
<script type="text/javascript">  
var pageTracker = _gat._getTracker("UA-xxxxxx-x");  
pageTracker._initData();  
pageTracker._trackPageview();  
</script>   
 )  

Replace UA-xxxxxx-x with the code found in the Javascript provided by Google Analytics. This example uses the new Google Analytics code replacing the old Urchin code.

Why does this work?

The following code shows how to do multiple line wrap, with all the content placed after the rest of the page content that has already been built by Typo3.

page.wrap (   
 | ...  
)

For multiple line values its important that the opening and closing rounded brackets are on their own line or it doesn’t take effect, likewise, make sure you don’t put in an equals = operator before the first opening curly bracket.

Note: Its recommended to have simulateStaticDocuments or realURL configured to be able to get the best kind of analysis with Google Analytics.