Skip to content

Instantly share code, notes, and snippets.

@jhpacker
Last active July 30, 2018 14:48
Show Gist options
  • Save jhpacker/099d8de85e0e815af1c03d70d4dec43a to your computer and use it in GitHub Desktop.
Save jhpacker/099d8de85e0e815af1c03d70d4dec43a to your computer and use it in GitHub Desktop.
Redact PII from Google Analytics (GTM)
// from https://brianclifton.com/blog/2017/09/07/remove-pii-from-google-analytics/
function() {
return function(model) {
// Add the PII patterns into this array as objects
var piiRegex = [
{
name: 'EMAIL',
regex: /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,
group: ''
},{
name: 'TEL',
regex: /((tel=)|(telephone=)|(phone=)|(mobile=)|(mob=))[\d\+\s][^&\/\?]+/gi,
group: '$1'
},{
name: 'NAME',
regex: /((firstname=)|(lastname=)|(surname=))[^&\/\?]+/gi,
group: '$1'
},{
name: 'PASSWORD',
regex: /((password=)|(passwd=)|(pass=))[^&\/\?]+/gi,
group: '$1'
},{
name: 'ZIP',
regex: /((postcode=)|(zipcode=)|(zip=))[^&\/\?]+/gi,
group: '$1'
},{
name: 'ADDRESS',
regex: /((address(\d)?=)|(street=))[^&\/\?]+/gi,
group: '$1'
}
];
// Fetch reference to the original sendHitTask
var originalSendTask = model.get('sendHitTask');
var i, hitPayload, parts, originalHitPayLoad, val;
// Overwrite sendHitTask with PII purger
model.set('sendHitTask', function(sendModel) {
hitPayload = sendModel.get('hitPayload').split('&');
originalHitPayLoad = sendModel.get('hitPayload').split('&');
try {
for (i = 0; i < hitPayload.length; i++) {
parts = hitPayload[i].split('=');
// Double-decode, to account for web server encode + analytics.js encode
try {
val = decodeURIComponent(decodeURIComponent(parts[1]));
} catch(e) {
val = decodeURIComponent(parts[1]);
}
//val = decodeURIComponent(unescape(parts[1]));
piiRegex.forEach(function(pii) {
val = val.replace(pii.regex, pii.group + '[REDACTED ' + pii.name + ']');
});
parts[1] = encodeURIComponent(val);
hitPayload[i] = parts.join('=');
}
sendModel.set('hitPayload', hitPayload.join('&'), true);
originalSendTask(sendModel);
}
catch(err) {
console.log("Error found: " + err.message);
hitPayload = sendModel.get('hitPayload');
sendModel.set('hitPayload', originalHitPayLoad, true);
originalSendTask(sendModel);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment