Skip to content

Instantly share code, notes, and snippets.

@LCHCAPITALHUMAIN
Forked from SNemzer/pii_removal_tag.html
Created June 7, 2021 11:06
Show Gist options
  • Save LCHCAPITALHUMAIN/377f60c99c89dfe214d9734c107d3ced to your computer and use it in GitHub Desktop.
Save LCHCAPITALHUMAIN/377f60c99c89dfe214d9734c107d3ced to your computer and use it in GitHub Desktop.
Custom HTML tag for GTM to strip PII from titles and URLs
<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