Set the value "img broken" in a GTM dataLayer on 404 image

95 Views Asked by At

I need to set a dataLayer event when a user view a broken image in the front end. I have a lot of errors in the console but I'm not able to pass this info into a dataLayer like:

dataLayer.push({
    'event': 'broken_img',
    'eventCategory': '404',
    'eventAction': 'Broken Img',
    'eventLabel': document.location.pathname
});

When the page is loaded. Any suggests for a generic JS or jQuery Code?

Thanks

1

There are 1 best solutions below

1
Michele Pisani On

Try this solution with onerror:

<img onerror="pushError(this.src)" src="https://mydomain/myimg.jpg">

window.dataLayer = window.dataLayer || [];

function pushError(src) {
  dataLayer.push({
      'event': 'broken_img',
      'eventCategory': '404',
      'eventAction': 'Broken Img',
      'eventLabel': src
  });
}