Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
UTM Parser for Marketo
//First, let's get the URI and have it split out all parameters
var getURLParams = function() {
var temp = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function() {
var decode = function(s) {
return decodeURIComponent(s.split("+").join(" "));
};
temp[decode(arguments[1])] = decode(arguments[2]);
});
return temp;
};
//Then, we'll take those parameters we temporarily saved and turn them into JS variables
var $_GET = getURLParams();
var utmMedium = getURLParams()["utm_medium"];
var utmSource = getURLParams()["utm_source"];
var utmCampaign = getURLParams()["utm_campaign"];
var utmTerm = getURLParams()["utm_term"];
var utmContent = getURLParams()["utm_content"];
var initPath = document.location.origin + document.location.pathname;
if (initPath.slice(-1)!="/"){
var initPath = initPath + "/";
}
//Now, time to tell Marketo what we want. Because associateLead (which writes directly into variables) needs us to both use SHA-1 generation and to have a known lead, this will not get the results we want. But even anonymous leads can visit URLs!
//But first: let's check if there's any valid UTM value before getting crazy here.
if(typeof utmSource=='string') {
Munchkin.munchkinFunction('visitWebPage', {
url: initPath + utmSource, params: utmSource
});
}
if(typeof utmMedium=='string') {
Munchkin.munchkinFunction('visitWebPage', {
url: initPath + utmMedium, params: utmMedium
});
}
if(typeof utmCampaign=='string') {
Munchkin.munchkinFunction('visitWebPage', {
url: initPath + utmCampaign, params: utmCampaign
});
}
if(typeof utmTerm=='string') {
Munchkin.munchkinFunction('visitWebPage', {
url: initPath + utmTerm, params: utmTerm
});
}
if(typeof utmContent=='string') {
Munchkin.munchkinFunction('visitWebPage', {
url: initPath + utmContent, params: utmContent
});
}
@chook

This comment has been minimized.

Copy link

@chook chook commented May 9, 2016

thanks for setting this up - how do you parse these in Marketo to change the value of utm custom fields?

@nduralt

This comment has been minimized.

Copy link

@nduralt nduralt commented Oct 10, 2017

So I spent the better part of a day figuring why this wasn't working through GTM and I realized that you can't fire it until it's DOM ready

@cougrimes

This comment has been minimized.

Copy link
Owner Author

@cougrimes cougrimes commented Oct 16, 2017

Hey @nduralt,

If you're working with GTM, there's definitely a faster way of processing this using the data layer rather than using this script (which is meant for vanilla instances, and as you note, requires DOM Ready)--you can just skip all the variable capturing, use GTM's variables, and have the script just do everything from line 30 on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment