0
votes

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.

1
Can you be more specific about what the URLs will look like? The purpose of UTM parameters is to track traffic's acquisition channels. By setting it once the user lands on the page, then you'll cause your tracking to be inaccurate and unnecessary sessions to be triggered. - XTOTHEL
Well the URLs will just be normal landing URLs from adsertisements so www.example.com/path/to/post. But once the user lands on the page we pull information about the post from our database, and therefore information that we'd like to send to analytics. - LucyTurtle
This is going to cause issues with GA. Also this isn’t UTM tracking. I don’t advise you doing it this way even if it is possible. Maybe try utilizing some custom dimensions. - XTOTHEL

1 Answers

-1
votes

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>