Skip to content

Instantly share code, notes, and snippets.

@yodametrics
Last active September 28, 2022 11:56
Show Gist options
  • Save yodametrics/3f79f8f0f0a3377f4c83ec75b55e09f1 to your computer and use it in GitHub Desktop.
Save yodametrics/3f79f8f0f0a3377f4c83ec75b55e09f1 to your computer and use it in GitHub Desktop.
<script>
(function() {
var xhrOpen = window.XMLHttpRequest.prototype.open;
var xhrSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.open = function() {
this.method = arguments[0];
this.url = arguments[1];
return xhrOpen.apply(this, [].slice.call(arguments));
};
window.XMLHttpRequest.prototype.send = function() {
var xhr = this;
var xhrData = arguments[0];
var intervalId = window.setInterval(function() {
if(xhr.readyState != 4) {
return;
}
dataLayer.push({
'event': 'ajaxSuccess',
'eventCategory': 'AJAX ' + xhr.method,
'eventAction': xhr.url + (xhr.method == 'POST' && xhrData ? ';' + xhrData : ''),
'eventLabel': xhr.responseText
});
clearInterval(intervalId);
}, 1);
return xhrSend.apply(this, [].slice.call(arguments));
};
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment