google-analyticsutm-tracking

Google Analytics UTM Tracking Without Variables in URL


I need to be able to track UTM parameters in Google Analytics without them being in the URL.

We load information when the page loads, and we want to use this information in our UTM parameters, and we don't want to redirect users to the URL with UTM variables appended.

I see on this page you can call a pageview with javascript, but I don't see anyway to specify utm parameters: https://developers.google.com/analytics/devguides/collection/analyticsjs/pages.


Solution

  • I simply used the Google gtag.js documentation on PageViews to edit the script that loads the inital pageview information.

    I first pull the current URL and append the variables to the end of the URL, and pass the new URL as the pageview to override the URL without the UTM parameters.

    I am using laravel so @if statements will work within the JS, and {{}} is echoing the variables.

    <script>
        var url = new URL( window.location.href );
        @if( isset( $request->utm_source ) )
            url.searchParams.set( 'utm_medium', '{{ strtolower( $request->utm_source ) }}' );
        @endif
        @if( isset( $request->utm_medium ) )
            url.searchParams.set( 'utm_medium', '{{ strtolower( $request->utm_medium ) }}' );
        @endif
        @if( isset( $request->utm_campaign ) )
            url.searchParams.set( 'utm_campaign', '{{ strtolower( $request->utm_campaign ) }}' );
        @endif
        @if( isset( $request->utm_term ) )
            url.searchParams.set( 'utm_term', '{{ strtolower( $request->utm_term ) }}' );
        @endif
        @if( isset( $request->utm_content ) )
            url.searchParams.set( 'utm_content', '{{ strtolower( $request->utm_content ) }}' );
        @endif
    
        function gtag() {
            dataLayer.push(arguments)
        }
        window.dataLayer = window.dataLayer || [], gtag("js", new Date), gtag("config", "GA_MEASUREMENT_ID", {
            'page_title': document.title,
            'page_location': url.href
        });
    </script>