Skip to content

Instantly share code, notes, and snippets.

@webag
Last active May 8, 2024 11:03
Show Gist options
  • Save webag/e7ee58ae662d74151d6205c422b4a9ef to your computer and use it in GitHub Desktop.
Save webag/e7ee58ae662d74151d6205c422b4a9ef to your computer and use it in GitHub Desktop.
UTM to forms
/* UTM to Forms Begin */
document.addEventListener('DOMContentLoaded', function () {
if (window.localStorage) {
const params = new URLSearchParams(window.location.search);
const utmParams = ['utm_source', 'utm_medium', 'utm_content', 'utm_campaign', 'utm_term'];
utmParams.forEach(param => {
const value = params.get(param);
if (value !== null && value !== "") {
localStorage.setItem(param, value);
}
});
} else {
console.error('No localStorage in window');
}
const forms = document.querySelectorAll('form');
forms.forEach(form => {
const utmParams = ['source', 'medium', 'content', 'term', 'campaign'];
utmParams.forEach(param => {
const input = document.createElement('input');
input.type = 'hidden';
input.name = `utm_${param}`;
input.value = localStorage.getItem(`utm_${param}`) || '';
form.appendChild(input);
});
});
});
/* UTM to Forms End */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment