+ Start a Discussion
Will M SmithWill M Smith 

Google Tag Manager and Lightning Community and Components

I've managed to import the Google Tag Manager code into the <head> using the lightning community settings tab. This loads perfectly fine and I can see the 'preview' window for google tag manager.

   
<!-- Google Tag Manager -->
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','GTM-XXXXXXX');</script>
    <!-- End Google Tag Manager -->



However, when I try to access the 'dataLayer' or 'window.dataLayer' object in a lightning component controller, it appears as undefined. I understand this is due to the SecureWindow that has been implemented.

For example:

   
addCourseToCart : function(component, event, helper) {
      dataLayer.push({
        'event': 'addToCart',
        'ecommerce': {
          'currencyCode': 'EUR',
          'add': {                                // 'add' actionFieldObject measures.
            'products': [{                        //  adding a product to a shopping cart.
              'name': 'Triblend Android T-Shirt',
              'id': '12345',
              'price': '15.25',
              'brand': 'Google',
              'category': 'Apparel',
              'variant': 'Gray',
              'quantity': 1
             }]
          }
        }
      });
    },



Is there still no way at all I can access the dataLayer using lightning communities and components? If not, this unfortunately makes it a nightmare for my customer to track in-depth interactions on their community... I'm surprised Salesforce have overlooked this...
MagulanDuraipandianMagulanDuraipandian
Check whether you have added it to the trusted sites.
https://developer.salesforce.com/blogs/2019/04/google-tag-manager-for-community-cloud.html
--
Magulan Duraipandian
www.infallibletechie.com