Last active
June 17, 2022 21:35
-
-
Save jkereako/d7d29226cba7287b50f1d1d7939d2772 to your computer and use it in GitHub Desktop.
Replace tokenized links with query string arguments.
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
function getQuery() { | |
const urlSearchParams = new URLSearchParams(window.location.search); | |
return Object.fromEntries(urlSearchParams.entries()); | |
} | |
function getAnchorTags() { | |
return document.getElementsByTagName('a'); | |
} | |
function getLinks() { | |
return Array.from(getAnchorTags()).map(el => { return el.href; }); | |
} | |
function replaceTokens(tokenizedStrings, obj) { | |
const keys = Object.keys(obj); | |
// Take no action if there's nothing to replace. | |
if (keys.length < 1 || tokenizedStrings.length < 1) { | |
return tokenizedStrings; | |
} | |
let processed = tokenizedStrings; | |
keys.forEach(key => { | |
processed = processed.map(str => { | |
return str.replaceAll(`{${key}}`, obj[key]); | |
}) | |
}); | |
return processed; | |
} | |
function replaceLinks() { | |
const links = getLinks(); | |
if (links.length < 1) { | |
console.error("Links not found"); | |
return; | |
} | |
const processedLinks = replaceTokens(links, getQuery()); | |
const anchorTags = getAnchorTags(); | |
// This algorithm fails otherwise | |
console.assert( | |
processedLinks.length === anchorTags.length, | |
"Arrays are unequal in length." | |
); | |
// Replace links | |
processedLinks.forEach((link, idx, _) => { | |
anchorTags.item(idx).href = link; | |
}); | |
} | |
// Execute the script. | |
document.onreadystatechange = () => { | |
if (document.readyState === "complete") { | |
replaceLinks(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Description
Replaces tokenized
href
attributes of all anchor tags on the current page with the corresponding value in the query string. The original purpose is to propagate query string values. It was a hack to support click attribution for an encumbered ad platform.Example
For the given URL:
http://example.com/mypage?utm_source=foo&utm_campaign=bar
And the given anchor tag on the current page:
<a href="http://asdf.com?utm_source={utm_source}">
This script will output the following:
<a href="http://asdf.com?utm_source=foo">