Last active
September 20, 2021 17:55
-
-
Save thyngster/a44cfc98e701884d15cbce58781eeb94 to your computer and use it in GitHub Desktop.
Remap Events Event Time Parameter as an Event Parameter
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() { | |
/* | |
* | |
* ( David Vallejo @thyng ) | |
* MIT License | |
* Remap _et ( Event Time ) as a customEvent Perameter | |
* | |
*/ | |
try { | |
// Monkey Patch, sendBeacon | |
var proxied = window.navigator.sendBeacon; | |
var remapEventTime = (payload)=> { | |
// object.entries polyfill | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#Polyfill | |
if (!Object.entries) | |
Object.entries = function(obj) { | |
var ownProps = Object.keys(obj) | |
, i = ownProps.length | |
, resArray = new Array(i); | |
// preallocate the Array | |
while (i--) | |
resArray[i] = [ownProps[i], obj[ownProps[i]]]; | |
return resArray; | |
} | |
; | |
var eventPayload = payload.replace(/(^\?)/, '').split("&").map(function(n) { | |
return n = n.split("="), | |
this[n[0]] = decodeURIComponent(n[1]), | |
this; | |
} | |
.bind({}))[0]; | |
if (eventPayload._et) | |
eventPayload["epn.event_time"] = eventPayload._et | |
return Object.keys(eventPayload).map(function(key) { | |
return (key) + '=' + encodeURIComponent(eventPayload[key]); | |
}).join('&'); | |
} | |
window.navigator.sendBeacon = function() { | |
if (arguments && arguments[0].match(/google-analytics\.com.*v\=2\&/)) { | |
var endpoint = arguments[0].split('?')[0]; | |
var query = arguments[0].split('?')[1]; | |
var beacon = { | |
endpoint: endpoint, | |
// Check for PII | |
query: remapEventTime(query), | |
events: [] | |
}; | |
// This is a multiple events hit | |
if (arguments[1]) { | |
arguments[1].split("\r\n").forEach(function(event) { | |
beacon.events.push(remapEventTime(event)); | |
}); | |
} | |
// We're all done, let's reassamble everything | |
arguments[0] = [beacon.endpoint, beacon.query].join('?'); | |
if (arguments[1] && beacon.events.length > 0) { | |
arguments[1] = beacon.events.join("\r\n"); | |
} | |
} | |
return proxied.apply(this, arguments); | |
} | |
; | |
} catch (e) { | |
// In case something goes wrong, let's apply back the arguments to the original function | |
return proxied.apply(this, arguments); | |
} | |
} | |
)(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment