Last active
June 7, 2021 11:06
-
-
Save SNemzer/d0b55271259a14653cce63d0634a6d99 to your computer and use it in GitHub Desktop.
Custom HTML tag for GTM to strip PII from titles and URLs
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
<script> | |
//Extract Parameters into array | |
function extractParams() { | |
var urlParams = {}, | |
match, | |
search = /([^&=]+)=?([^&]*)/g, | |
query = window.location.search.substring(1); | |
while (match = search.exec(query)) { | |
urlParams[match[1]] = match[2]; | |
} | |
return urlParams | |
} | |
var urlParams = extractParams() | |
//Get list of parameters to retain from GTM variable | |
var usefulParams = {{parameterWhitelist}} | |
//Regex that defines email addresses | |
var emailRegex = /(([^<>()\[\]\\.,;:\s@"%]+(\.[^<>()\[\]\\.,;:\s@"%]+)*)|(".+"))(@|%40)((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/ | |
for (var key in urlParams) { | |
//Check for and retain whitelisted parameters | |
if (usefulParams.indexOf(key) == -1) { | |
delete urlParams[key] | |
} | |
//Redact email address by regex | |
else { | |
urlParams[key] = decodeURIComponent(urlParams[key]).replace(emailRegex, "EMAIL_REDACTED") | |
} | |
} | |
//Rewrite URL | |
function rewriteURL(urlParams) { | |
var keys = Object.keys(urlParams).sort(); | |
if (keys.length == 0) { | |
return window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.hash | |
} | |
var params = "?"; | |
for (var i = 0; i < keys.length; i++) { | |
if (i > 0) { | |
params = params.concat("&") | |
} | |
params = params.concat(keys[i] + "=" + urlParams[keys[i]]) | |
} | |
return window.location.protocol + "//" + window.location.host + window.location.pathname + params + window.location.hash | |
} | |
var newURL = rewriteURL(urlParams); | |
if (newURL !== window.location.href) { | |
//History Change URL | |
window.history.replaceState({}, document.title, newURL) | |
} | |
//Redact emails in title tags | |
var newTitle = document.title.replace(emailRegex, "EMAIL_REDACTED"); | |
if (newTitle !== document.title) { | |
document.title = newTitle | |
} | |
//Push to dataLayer | |
dataLayer.push({ | |
event: "parametersRemoved" | |
}) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment