Skip to content

Instantly share code, notes, and snippets.

@chrisle chrisle/answer.js
Created Dec 7, 2016

Embed
What would you like to do?
/**
* To answer @AnnieCushing's question on Twitter:
* https://twitter.com/AnnieCushing/status/806518054368739329
*
* Author: Chris Le - @iamchrisle
*
* There's a few ways to do this.
* - Like @SimoAhava suggested, server redirects that strips parameters if you
* have the ability to control the server.
*
* Here's a JavaScript / GTM solution if you only have the ability to change
* the code on the pages: Use the DataLayer to hold either the
* UTM campaigns if the referrer is or is not "primarydomain.com".
*
* This code would go on every page near the GTM tag.
*
* Technically speaking if you have nothing but access to GTM and GA, you could
* also sneak this code into a custom HTML tag.
*
* So.. this would go into the page...
*/
(function() {
var getParameterByName = function(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
if (document.referrer.indexOf('primarydomain.com') == -1) {
window['dataLayer'].push({
utmVariables: {
campaignSource: getParameterByName('utm_source'),
campaignCampaign: getParameterByName('utm_campaign'),
campaignMedium: getParameterByName('utm_medium'),
campaignTerm: getParameterByName('utm_term'),
campaignContent: getParameterByName('utm_content')
}
});
} else {
window['dataLayer'].push({
utmVariables: {
campaignSource: '',
campaignCampaign: '',
campaignMedium: '',
campaignTerm: '',
campaignContent: ''
}
});
}
})();
//////////////////////////////////////////////////////
/**
* Then in GTM create a few dataLayer variables that pulls that stuff.
*
* One variable named "UTM Source"
* Data Layer variable name: "utmVariables.campaignSource"
* Data Layer version: 2
*
* One variable named "UTM Campaign"
* Data Layer variable name: "utmVariables.campaignName"
* Data Layer version: 2
*
* ... and so on for all 5 variables.
*/
/**
* Finally, in your Google Analytics tag, under "more settings", "fields to set"
* add them:
*
* +-----------------+--------------------+
* | Field name | Value |
* +-----------------+--------------------+
* | campaignSource | {{ UTM Source }} |
* | campaignName | {{ UTM Campaign }} |
* | ..... so on. | |
* +-----------------+--------------------+
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.