Skip to content

Instantly share code, notes, and snippets.

@rolandfarkasCOM
Created March 1, 2022 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rolandfarkasCOM/cd45d6a7814d2eb2abe1710fea952211 to your computer and use it in GitHub Desktop.
Save rolandfarkasCOM/cd45d6a7814d2eb2abe1710fea952211 to your computer and use it in GitHub Desktop.
JS - Typeform - Pass UTM & Click ID (Google, Facebook, Microsoft) to Iframe
!function (window, document, undefined) {
document.addEventListener('DOMContentLoaded', function() {
var urlParams;
var parser = document.createElement('a');
var pattern = /utm_|gclid|fbclid|msclkid/i;
parser.href = window.location.href.replace('%20#', '?').toLowerCase();
if (pattern.test(parser.href)) { // url contains utms
var utms = window
.location
.search
.replace('?','')
.split('&')
.reduce(
function(p,e){
var a = e.split('=');
p[decodeURIComponent(a[0]).toLowerCase()] = decodeURIComponent(a[1]);
return p;
},
{}
);
// create params string
urlParams = createUtmsparams(utms);
if (typeof urlParams === 'undefined' || !urlParams) {
return;
} else {
// find all links for changing
var links = document.querySelectorAll("a");
var i; var pattern = /typeform.com/;
for (i = 0; i < links.length; i++) {
var link = links[i].href;
// change typeform links only
if (pattern.test(link)) {
link = (link.indexOf('?') != -1) ? link + '&' : link.replace(/\/+$/, '') + '/?';
links[i].href = link + urlParams;
}
}
}
}
});
function createUtmsparams (utms) {
var checkObj = ['utm_campaign', 'utm_source', 'utm_medium', 'utm_conttent', 'utm_term', 'gclid', 'fbclid', 'msclkid'];
var selfUtms = [];
Object.keys(utms)
.map(function(k) {
if (checkObj.includes(k)) {
selfUtms.push(encodeURIComponent(k) + '=' + encodeURIComponent(utms[k]));
}
});
return selfUtms.join('&');
}
}(window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment