Campaign variables are key for tracking referral data and the best part is that they come “free” out-of-box in Google Analytics (GA). All you need to do is tack on the Urchin Traffic Monitor (UTM) parameters to your URL and you’re set.
What if you needed to change these variables in JS? This is easy to do.
How do I get started?
Setting campaign variables in classic GA is generally well-documented, but with Universal Analytics many examples don’t seem to exist (I think).
Below is an example of how you can change them programmatically with JS. It all starts with the GA snippet and using the ‘set’ function to override GA properties/options:
- //General GA Snippet
- (i[r].q=i[r].q||).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
- //Your GA ID
- //Set/override the mandatory parameters -
- //Set/override the optional parameters
- ga('set','campaignKeyword','Blue Shoes');
- //send the pageview after variables are set
Notice the “keys” (second parameters after the ‘set’ parameter) that are available correspond to the UTM parameters:
Please note that you have to override the parameters before the pageview is sent, otherwise the settings will not register properly. To know if you’ve set these vars up properly, just pop open the “Traffic Sources” section in Google Analytics Real-Time and see the Campaign variables be tracked/changed as you specified in your JS.
Why would I want to do this?
I’m sure there are many more reasons when this is needed, but there are some situations where campaign variables are not or cannot be set directly from the querystring or there has to be some additional processing of parameters that need to happen.
For example, if you’re building a Facebook iFrame App within a Tab you want to be able to track referrers. So using the querystring UTM parameters to link directly to your GA account within the iFrame is not exactly straightforward. So for example, you’d have to parse out the “app_data” parameter with your custom vars, then in your application change/set the GA campaign parameters with JS.