How to use google analytics in TYPO3?

You can use a simple typoscript snippet to add google analytics to TYPO3

We have been using numerous google analytics extensions for typo3 over the years. However we still think I might be a good idea to create one purely based on typoscript and add a goal. This way we can keep track of how many users see the actualy "thank you"-page which is an important metric to us. We use this metric to decide if the sales funnel is correct and what changes need to be made. In our specific case we want user to sign up for something, and we added a lot of buttons pointing to this page. This page has a form and if the form is filled, the contents are mailed an the user is redirected to a specific page. We know this should be done in Google Tag Manager (GTM) now, but we still prefer the older way untill we migrate to GTM.

We use this typoscript library to add some javascript to the lib.


lib.googleanalytics = COA
lib.googleanalytics {
     10 = TEXT
    10.value (
        <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','https://www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-YOURCODEHERE', 'auto');
    )
    30 = TEXT
    30.value (
        ga('send', 'pageview');
        </script>
    )
}

[globalVar = TSFE:id = YOURPAGEIDHERE]
lib.googleanalytics.20 = TEXT
lib.googleanalytics.20.value (
    ga('send', 'event', { eventCategory: 'Contact', eventAction: 'Submit', eventLabel: 'Contact Page Form', eventValue: 1});
)
[global]

After this, we will include the lib.googleanalytics in our main setup.ts


<INCLUDE_TYPOSCRIPT: source="FILE: fileadmin/YOURPATH/lib.googleanalytics.ts">

And we include the library in our footer partial like this.


<f:cObject typoscriptObjectPath="lib.googleanalytics"/>

This way the google analytics code is loaded really late in the DOM which also helps page rendering times.

Created by Daniel on 11/22/2024

Copyright © DanielKnows.com 2019 - 2024 - Built with NuxtJS

Subscribe for Tech Tips!

Stay updated with the latest tech insights and tips. Subscribe now!

{}