Created
September 27, 2023 17:00
-
-
Save javanigus/0dd130e4b852025a56ad98d60cab7783 to your computer and use it in GitHub Desktop.
Save UTM params in URL as session cookies; append UTM params to links with "appendUTM" class
This file contains 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
/* | |
* save UTM parameters in URL as session cookies | |
* if a link contains the class "appendUTM", | |
* then append the UTM params to the link | |
*/ | |
(function () { | |
"use strict"; | |
// get url query string parameters | |
var urlParams = qualys.parseQueryString(window.location.search); | |
// loop over each url query string parameter | |
Object.entries(urlParams).forEach(([key, value]) => { | |
// console.log(`${key}: ${value}`); | |
key = key.toLowerCase(); | |
// if the parameter is a UTM parameter | |
if (key.startsWith("utm_")) { | |
// set a session cookie for UTM parameter | |
document.cookie = [ | |
`qualys.${key}=${value}`, | |
//"domain=.qualys.com", | |
"path=/", | |
"secure=yes" | |
].join("; "); | |
} | |
}); | |
// get all cookies | |
var cookies = qualys.parseCookieString(document.cookie); | |
var utms = []; | |
// loop over each cookie | |
cookies.forEach((cookie) => { | |
// save each UTM cookie in the utms array | |
if (cookie.name.startsWith("qualys.utm_")) { | |
var utmName = cookie.name.replace("qualys.", ""); | |
var obj = {}; | |
obj[utmName] = cookie.value; | |
utms.push(obj); | |
} | |
}); | |
// console.log(utms); | |
// find all links in page that have the class "appendUTM" | |
var elements = document.querySelectorAll('.appendUTM'); | |
// convert NodeList to array | |
var links = Array.from(elements); | |
var link; | |
// loop over matching links | |
for (link of links) { | |
// get the link href value | |
var href = link.getAttribute('href'); | |
var url = new URL(href); | |
// loop over each UTM parameter found in cookies | |
for (const index in utms) { | |
// console.log(index, utms[index]); | |
for (const [key, value] of Object.entries(utms[index])) { | |
// console.log(key, value); | |
// set the utm name/value pair in the query string | |
url.searchParams.set(key, value); | |
} | |
} | |
// console.log(url.href); | |
// update the href value | |
link.setAttribute('href', url.href); | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment