3

I'm fairly new to Salesforce and Lightning Components, so please bear with me. I have a test Lightning Component named ajAppComponent and want to embed Google Analytics in the component.

First, I added https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-1 as a static resource named GoogleAnalytics. I've also added https://www.google-analytics.com/analytics.js as analytics.

In my ajAppComponent.cmp file, I've added the following line:

<ltng:require scripts="{!'/resource/GoogleAnalytics'}" afterScriptsLoaded="{!c.gaLoaded}" />

I've also tried it loading the analytics static resource, but that didn't help either.

In my ajAppComponentController.js I have the gaLoaded function, which has:

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXXX-1');

But neither show any activity in my Google Analytics homepage. I know it's loading the gaLoaded function as I've put in debugging code (console.log) and I see the resource loaded when I look in Google Dev Tools.

Am I missing a step somewhere? Any help would be greatly appreciated!

2
+25

You are missing out the send step as mentioned here here.

Sends a hit to Google Analytics. The fields that are sent are the values specified in the ...fields parameters and fieldsObject, merged with the fields currently stored on the tracker.

here is my sample code of afterScriptLoaded

afterScriptLoaded: function (component) {
        // store the name of the Analytics object
        window.GoogleAnalyticsObject = 'ga';
        // check whether the Analytics object is defined
        if (!('ga' in window)) {
            // define the Analytics object
            window.ga = function () {
                // add the tasks to the queue
                window.ga.q.push(arguments);
            };

            // create the queue
            window.ga.q = [];
        }
        // store the current timestamp
        window.ga.l = (new Date()).getTime();
        window.ga_debug = {
            trace: true
        };
        debugger;


        ga('create', trackingid, {
            'userId': userdata.name,
            'storage': 'none',
            'dimension3': userdata.name,
            'dimension4': userdata.accountName
        });
        ga('send', 'pageview');

    }
  • Which script do you run as a static resource? Also, would I replace "trackingid" with my own tracking ID? I added your code and when I go to Google Analytics "Real Time" I still don't see any activity. Thank you! – ajtatum Sep 19 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.