MattiaLD
MattiaLD

Reputation: 1

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

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

Upvotes: 0

Views: 99

Answers (1)

Michele Pisani
Michele Pisani

Reputation: 14179

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
  });
}

Upvotes: 0

Related Questions