Skip to main content
  1. Blog Post/

Track alert() pop ups automatically in Google Tag Manager

2 min · 390 words

Did you ever faced a site that still used the old-fashined alert popups for example for showing a form validation messages? and you were wondering how to track that form alert popups without needing to change anything on the site (as it is likely going to be an old one). And yep,they still exist. Hopefully if we are already using Google Tag Manager (or we can tell the client to add some little piece of code to their pages) we could track them easily using what is called a Proxy Pattern.

Sadly this won't be supported by IE8 for the alerts as it seems it's not a function but an object, therefore we're adding a check for pre IE9 browsers.

In essence, we're saving the current window["alert"] function in a new variable, and the redefining the same function, but returning the passed arguments to our original saved function, preserving the original function behaviour.

We'll just need to create a Custom Html Tag that will fire either in all pages or just for the ones that we want to track alerts on.

// Let's check if the browser is <=IE8
if(!(document.all && !document.addEventListener))
{ 
 // Just in case check, to avoid loops
 if(!window.proxied_alert)
 {
   window.proxied_alert = window.alert; // Preserve the original function
   window.alert = function() { 
     var message = (!arguments[0]) ? 'null': arguments[0];
     dataLayer.push({'event': 'alert_showed','alert_message': message});
     return proxied_alert.apply(this, arguments);
   }
 }
}

In this example we're pushing the info to the dataLayer, but we could directly do anything like firing an event using the native ga/_gaq functions or pushing the info to any other tool we want.

As we're modifying the original window.alert function, I suggest  to deeply debug/test the site functionality after implementing this code, as it may happen that other script is doing the same thing to the alert function. (some modals scripts plays with this to automatically convert the alert calls to a nicer popups).