javascripthtmlgoogle-analyticstrackingvwo

Track visitors across different domains using Google Analytics


We provide a <div> block to our clients to put on their websites, which they then integrate into their site using a script that will generate the html.

For example:

<div class="currentDiv">

<script type="text/javascript" id="axxaax99" src="xxxx-xxx.js"></script>

</div>

How do I track the number of visitors in Google Analytics, through our <div> block that is placed on our clients websites?


Solution

  • I was able to solve this and I want to share my solution to save other people time.

    so first thing to do on client website is to check if google analytics is already there or we load it and then you can fire a page-event send using the tracker name that you already created.

    <script type="text/javascript">
                
    var appendAnalytics = function (i, s, o, g, r, cb) {
                    i["GoogleAnalyticsObject"] = r;
    i[r] = i[r] || function () {
    (i[r].q = i[r].q || []).push(arguments)}, i[r].l = 1 * new Date();
    var a = s.createElement(o);
    var m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    
    a.onload = cb;
    m.parentNode.insertBefore(a, m)};
    
    if (window.ga === undefined) {
    
    appendAnalytics(window, document, "script", "//www.google-analytics.com/analytics.js", "ga", sendPageView);
    } else {
    
    sendPageView();
    }
    
    function sendPageView() {
    
    window.ga("create", "UA-XXXXXX”, "auto", {
    name: “YourTrackerName”
                    });
    window.ga("YourTrackerName.send", "pageview");
    
    }
    
    </script>