Track all outbound links in Google Analytics

前端 未结 7 1807
小蘑菇
小蘑菇 2021-01-31 20:06

I\'ve been using a script to track outbound links for a couple of months now. The script WORKS, but in the report generated by Google Analytics many UR

7条回答
  •  伪装坚强ぢ
    2021-01-31 20:53

    Here's my solution using Google suggested code

    Put this right after your GA tracking code (probably in )

    // TRACK OUTBOUND LINKS
    document.addEventListener("DOMContentLoaded", function() {
        var trackOutboundLink = function(url) {
           ga('send', 'event', 'outbound', 'click', url, {
             'transport': 'beacon',
             'hitCallback': function(){document.location = url;}
           });
        }
    
        var a = document.getElementsByTagName('a');
    
        for(i = 0; i < a.length; i++){
            if (a[i].href.indexOf(location.host) == -1 && a[i].href.match(/^http?s:\/\//i)){
                a[i].onclick = function(){
                    trackOutboundLink(this.href);
                }
            }
        }
    });
    // END
    

提交回复
热议问题