AdSense Ads Click Tracking with Google Tag Manager and Google Analytics

Tracking clicks on Google display ads (AdSense Ad) can be tricky because it comes as an iframe. Traditional methods like link clicks or button clicks won’t work, and typical JavaScript event listener codes might fail. In this tutorial, I’ll guide you step by step on how to track AdSense Ads events accurately using a revolutionary code with Google Tag Manager and Google Analytics.

AdSense Ads Click Tracking DataLayer Code

/**
* Author: Md Hasanuzzamna
* Linkedin: https://linkedin.com/in/md-h
* Youtube: https://youtube.com/@leomeasure
* Email: info@leomeasure.com
*/

(function() {
    var isAdsArea = false;
    var ad_link = '';
    var page_link = window.location.href;

    document.addEventListener('mouseover', function (e) {
        var target = e.target.closest('iframe[src^="https://googleads.g.doubleclick.net"]');
        var target2 = e.target.closest('iframe[src$="/html/container.html"]');

        if(target) {
            isAdsArea = true;
            ad_link = target.getAttribute('src');
        }else if(target2) {
            isAdsArea = true;
            ad_link = target2.getAttribute('src'); 
        }
        else {
            isAdsArea = false;
            ad_link = '';
        }
    });

    window.addEventListener('blur', function () {
        if(isAdsArea) {
            window.dataLayer = window.dataLayer || [];
            dataLayer.push({
                'event': 'adsense_ad_click',
                'ad_link': ad_link,
                'ad_location': page_link
            })
        }
    });
})();

Leave a Comment

Your email address will not be published. Required fields are marked *

Contact Us

Please contact us for expert guidance & personalized solutions to maximizing the potential of Google Analytics for your business.

Send Us A Message