Created
January 23, 2017 23:44
-
-
Save hedleysmith/f931e056d372ea5553c44ab08bee80f6 to your computer and use it in GitHub Desktop.
Store UTM params & referrer UTL as subscriber fields on MailChimp form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// $(document).ready() replacement. | |
function ready(fn) { | |
if (document.readyState != 'loading'){ | |
fn(); | |
} else { | |
document.addEventListener('DOMContentLoaded', fn); | |
} | |
} | |
// Get UTM params from URL to pass to Mailchimp. Store in localStorage so they follow the user around the site. | |
function getParameterByName(name) { | |
// First try url params. | |
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); | |
var regexS = "[\\?&]" + name + "=([^&#]*)"; | |
var regex = new RegExp(regexS); | |
var results = regex.exec(window.location.search); | |
if (results == null) { | |
// Try localStorage if no url params. | |
var storedParam = localStorage.getItem(name); | |
if (storedParam) { | |
return storedParam; | |
} | |
return ""; | |
} else { | |
return decodeURIComponent(results[1].replace(/\+/g, " ")); | |
} | |
} | |
function storeUTMParams(name) { | |
var utmParam = getParameterByName(name); | |
if (utmParam) { | |
localStorage.setItem(name, utmParam); | |
} | |
} | |
ready(function () { | |
var formTarget = document.getElementById("mc-embedded-subscribe-form"); | |
function addFormElem(paramName, fieldName) { | |
var paramValue = getParameterByName(paramName); | |
var utmEl = "<input type='hidden' name='" + fieldName + "' value='" + paramValue + "' />"; | |
if (paramValue != "" && formTarget) { | |
formTarget.insertAdjacentHTML('afterbegin', utmEl) | |
} | |
} | |
// Note: Only change the values after ":" if they are different for you | |
// They are the same one as you added in your email marketing provider | |
var utmParams = { | |
"utm_source" : "USOURCE", | |
"utm_medium" : "UMEDIUM", | |
"utm_campaign" : "UCAMPAIGN", | |
"utm_content" : "UCONTENT", | |
"utm_term" : "UTERM" | |
}; | |
for (var param in utmParams) { | |
addFormElem(param, utmParams[param]); | |
storeUTMParams(param); | |
} | |
// Also add referrer. | |
if (formTarget) { | |
var referredElm = "<input type='hidden' name='REFERRER' value='" + window.location.href.split('?')[0] + "' />"; | |
formTarget.insertAdjacentHTML('afterbegin', referredElm); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment