Last active
May 26, 2021 07:44
-
-
Save jasperkennis/10361d130e4d6fb9a9d885775dedcb89 to your computer and use it in GitHub Desktop.
Replace some url params with others
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
<!-- Place this just before the closing tag of <body> --> | |
<script> | |
(function(){ | |
function getParams () { | |
const paramsToReplace = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term']; | |
const res = []; | |
const windowParams = new URLSearchParams(window.location.search); | |
for (let i = 0; i < paramsToReplace.length; i++) { | |
const paramName = paramsToReplace[i]; | |
if (windowParams.has(paramName)) { | |
res.push({ | |
name: paramName, | |
value: windowParams.get(paramName) | |
}) | |
} | |
} | |
return res; | |
} | |
function replaceValues (existingValues, replacementParams) { | |
if (existingValues == null) { | |
existingValues = ''; | |
} | |
const existingParams = new URLSearchParams(existingValues); | |
for (let i = 0; i < replacementParams.length; i++) { | |
const replacementParam = replacementParams[i]; | |
existingParams.set( | |
replacementParam.name, | |
replacementParam.value | |
) | |
} | |
return existingParams; | |
} | |
function prepareLinks() { | |
const replacementParams = getParams(); | |
const links = document.getElementsByTagName('a'); | |
for (let i = 0; i < links.length; i++) { | |
const thisLink = links[i]; | |
if (!thisLink.hasAttribute('href')) { | |
continue; | |
} | |
const currentHrefParts = thisLink.getAttribute('href').split('?'); | |
currentHrefParts[1] = replaceValues(currentHrefParts[1], replacementParams); | |
thisLink.setAttribute('href', currentHrefParts.join('?')) | |
} | |
} | |
try { | |
prepareLinks() | |
} catch (error) { | |
console.error('Failed to replace google tags.'); | |
console.error(error); | |
} | |
})() | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment