Skip to content

Instantly share code, notes, and snippets.

@OrenBochman
Created March 22, 2016 09:54
Show Gist options
  • Save OrenBochman/7f08a5879a4195dbe1fe to your computer and use it in GitHub Desktop.
Save OrenBochman/7f08a5879a4195dbe1fe to your computer and use it in GitHub Desktop.
custom GTM javascript variables
// Variable Name: ImageCounter
function () {
return function (imageFileName) {
var count = 0;
var images = document.getElementsByTagName('img');
var i;
for (i = 0; i < images.length; i++) {
var filePathParts = (images[i].src || '').split('/');
var fileName = filePathParts[filePathParts.length - 1];
if (fileName === imageFileName) {
count++;
}
}
return count;
}
}
// Variable Name: Custom Script Error Catcher
function() {
return function (name, functionToExecute) { // Name is used for identifying the function later on
try {
return functionToExecute();
} catch (err) {
if({{Debug Mode}}) {
console.dir(err); // Logs the error event object
}
if(!{{Debug Mode}}) { // Prevents errors from throwing during testing
var msg;
if(typeof err.lineNumber !== 'undefined') {
var fields = ['fileName', 'lineNumber', 'column', 'message'];
var values = [];
for(i = msg.length - 1; i > -1; i--) {
var _field = fields[i];
if(err[_field]) {
values.push(err[_field]);
}
};
msg = values.join(':');
} else if(err.stack) {
msg = err.stack.toString().replace(/^\s+|\s+$/, '');
} else {
var errName = err.name ? err.name + ':' : '';
var errMessage = err.message || "No message found.";
msg = errName + errMessage;
}
window.dataLayer.push({ // Fires an Event to a special QA property we receive reports from
'event': 'customError',
'attributes': {
'customError': {
'functionName': name,
'errorMessage': msg
}
}
});
}
return undefined;
}
};
}
@OrenBochman
Copy link
Author

based on lunametrics blog

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment