Skip to content

Instantly share code, notes, and snippets.

@Soben
Last active October 12, 2022 20:53
Show Gist options
  • Save Soben/177fd27d77f968814ca15893842e01d1 to your computer and use it in GitHub Desktop.
Save Soben/177fd27d77f968814ca15893842e01d1 to your computer and use it in GitHub Desktop.
GET Query Passthrough Handling
/**
* Querystring Passthrough
* Allows UTM values to stickaround on the site until needed.
*/
{
const allowedPassthrough = [
"utm_medium",
"utm_source",
"utm_campaign",
"utm_content",
"utm_term",
/* any GET query variables, */
]
const allowedDomains = [
window.location.host,
/* otherurl.com, */
]
const allowAbsoluteURls = true
const generatePassthroughQuery = function(urlQueryString) {
const urlQueryParams = new URLSearchParams(urlQueryString)
const matchedParamsQuery = []
urlQueryParams.forEach(function (value, key) {
// We're trying to passthrough this key/value pair.
if (allowedPassthrough.indexOf(key) !== -1) {
matchedParamsQuery.push(key + "=" + value)
}
})
if (matchedParamsQuery.length <= 0) {
return false
}
let matchedParamsQueryString = matchedParamsQuery.join("&")
return matchedParamsQueryString
}
const hrefPassthrough = function(urlQueryString) {
// get the passthroughQuery
let query = generatePassthroughQuery(urlQueryString)
if (!query) {
// if passthroughQuery is not available, then we're done.
return
}
document.querySelectorAll("a[href]").forEach(function (element) {
// Only process allowedDomains
let isAllowedDomain = false
for (let i = 0; i < allowedDomains.length; i++) {
if (element.href.indexOf(allowedDomains[i]) !== -1) {
isAllowedDomain = true
break
}
}
if (allowAbsoluteURls && element.href.indexOf("/") === 0) {
// We're dealing with an absolute URL, therefore always supported.
isAllowedDomain = true
}
// We didn't find a match
if (!isAllowedDomain) {
return
}
// Append the query and assign to the element's href.
element.href = element.href + (element.href.indexOf("?") === -1 ? "?" : "&") + query
})
}
// Set up the HREF updates
hrefPassthrough(window.location.search)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment