GA4 Event Tracking on Squarespace | Blue Frog Docs

GA4 Event Tracking on Squarespace

Configure custom event tracking for Squarespace-specific interactions including Commerce events, form submissions, and member area activities.

GA4 Event Tracking on Squarespace

Beyond basic page view tracking, GA4 can capture specific user interactions on your Squarespace site. This guide covers Squarespace-specific event tracking including forms, Commerce actions, and member area interactions.


Automatic Enhanced Measurement Events

GA4's Enhanced Measurement automatically tracks several events without additional code:

Enabled by Default:

  • Page views - Every page load
  • Scrolls - 90% scroll depth
  • Outbound clicks - Links to external domains
  • Site search - Squarespace search queries (if search is enabled)
  • Video engagement - YouTube and Vimeo videos (embedded via Squarespace blocks)
  • File downloads - PDF, DOC, XLS, etc.

Verify Enhanced Measurement

  1. In GA4, go to Admin > Data Streams
  2. Click your web stream
  3. Click Enhanced measurement
  4. Ensure relevant events are toggled on

Squarespace Form Submissions

Squarespace forms don't automatically send events to GA4. You need to implement custom tracking.

Method 1: Using Code Injection (Simple)

Add to Settings > Advanced > Code Injection > Footer:

<script>
  // Track Squarespace form submissions
  document.addEventListener('DOMContentLoaded', function() {
    // Listen for Squarespace form submission success
    window.addEventListener('message', function(e) {
      if (e.data && e.data.type === 'hsFormCallback' && e.data.eventName === 'onFormSubmitted') {
        // Form submitted successfully
        if (typeof gtag !== 'undefined') {
          gtag('event', 'form_submit', {
            'form_name': 'contact_form',
            'form_destination': window.location.pathname
          });
        }
      }
    });

    // Alternative: Monitor form submission via class change
    var forms = document.querySelectorAll('.sqs-block-form');
    forms.forEach(function(form) {
      var submitButton = form.querySelector('button[type="submit"]');
      if (submitButton) {
        submitButton.addEventListener('click', function() {
          // Wait for submission
          setTimeout(function() {
            var successMessage = form.querySelector('.form-submission-text');
            if (successMessage && successMessage.style.display !== 'none') {
              if (typeof gtag !== 'undefined') {
                gtag('event', 'form_submit', {
                  'form_name': getFormName(form),
                  'form_location': window.location.pathname
                });
              }
            }
          }, 1000);
        });
      }
    });

    function getFormName(formElement) {
      // Try to extract form name from heading above form
      var block = formElement.closest('.sqs-block');
      var heading = block ? block.querySelector('h1, h2, h3') : null;
      return heading ? heading.textContent.trim() : 'unknown_form';
    }
  });
</script>

If you have Google Tag Manager installed:

  1. Create a Custom HTML tag with form tracking code
  2. Use the Form Submission trigger
  3. Send GA4 event with form details

See GTM Setup Guide for implementation details.


Newsletter Signup Tracking

For Squarespace Newsletter blocks:

<script>
  document.addEventListener('DOMContentLoaded', function() {
    // Track newsletter signups
    var newsletterBlocks = document.querySelectorAll('.sqs-block-newsletter');

    newsletterBlocks.forEach(function(block) {
      var form = block.querySelector('form');
      if (form) {
        form.addEventListener('submit', function(e) {
          if (typeof gtag !== 'undefined') {
            gtag('event', 'newsletter_signup', {
              'method': 'squarespace_newsletter',
              'location': window.location.pathname
            });
          }
        });
      }
    });
  });
</script>

Commerce Events

Squarespace Commerce has specific interactions that should be tracked for eCommerce analysis.

Add to Cart

Track when users add products to cart:

<script>
  // Track Add to Cart
  (function() {
    if (window.Y && window.Y.Squarespace) {
      window.Y.use(function(Y) {
        Y.on('cart:item:added', function(e) {
          var item = e.item;

          if (typeof gtag !== 'undefined') {
            gtag('event', 'add_to_cart', {
              'currency': 'USD', // Update to your currency
              'value': item.price / 100, // Squarespace stores price in cents
              'items': [{
                'item_id': item.id,
                'item_name': item.title,
                'quantity': item.quantity,
                'price': item.price / 100
              }]
            });
          }
        });
      });
    }
  })();
</script>

Remove from Cart

<script>
  // Track Remove from Cart
  (function() {
    if (window.Y && window.Y.Squarespace) {
      window.Y.use(function(Y) {
        Y.on('cart:item:removed', function(e) {
          var item = e.item;

          if (typeof gtag !== 'undefined') {
            gtag('event', 'remove_from_cart', {
              'currency': 'USD',
              'value': item.price / 100,
              'items': [{
                'item_id': item.id,
                'item_name': item.title,
                'quantity': item.quantity,
                'price': item.price / 100
              }]
            });
          }
        });
      });
    }
  })();
</script>

Begin Checkout

Track when users start the checkout process:

<script>
  // Track Begin Checkout
  document.addEventListener('DOMContentLoaded', function() {
    // Detect checkout page
    if (window.location.pathname.includes('/checkout')) {
      // Get cart data
      if (window.Y && window.Y.Squarespace) {
        window.Y.use(function(Y) {
          var cartData = Y.Squarespace.Commerce.getCart();

          if (cartData && typeof gtag !== 'undefined') {
            var items = cartData.entries.map(function(entry) {
              return {
                'item_id': entry.id,
                'item_name': entry.title,
                'quantity': entry.quantity,
                'price': entry.price / 100
              };
            });

            gtag('event', 'begin_checkout', {
              'currency': 'USD',
              'value': cartData.subtotal / 100,
              'items': items
            });
          }
        });
      }
    }
  });
</script>

Note: For complete eCommerce tracking including purchases, see Squarespace Commerce + GA4 Ecommerce Tracking.


Member Area Events

For Squarespace sites with Member Areas, track member-specific interactions.

Member Login

<script>
  // Track Member Login
  (function() {
    if (window.Squarespace && window.Squarespace.user) {
      window.Squarespace.onInitialize(Y, function() {
        // Check if user just logged in
        var wasLoggedIn = sessionStorage.getItem('member_logged_in');
        var isLoggedIn = Y.Squarespace.User.isLoggedIn();

        if (isLoggedIn && !wasLoggedIn) {
          if (typeof gtag !== 'undefined') {
            gtag('event', 'login', {
              'method': 'squarespace_member_area'
            });
          }
          sessionStorage.setItem('member_logged_in', 'true');
        } else if (!isLoggedIn) {
          sessionStorage.removeItem('member_logged_in');
        }
      });
    }
  })();
</script>

Member Content Access

Track when members access restricted content:

<script>
  document.addEventListener('DOMContentLoaded', function() {
    // Check if page is member-only
    var isMemberPage = document.body.classList.contains('member-area') ||
                       document.querySelector('.sqs-member-only-content');

    if (isMemberPage && typeof gtag !== 'undefined') {
      gtag('event', 'member_content_access', {
        'content_type': 'member_only',
        'page_path': window.location.pathname
      });
    }
  });
</script>

Button Click Tracking

Track specific button clicks (CTAs, downloads, etc.):

<script>
  document.addEventListener('DOMContentLoaded', function() {
    // Track button clicks with specific classes or text
    var buttons = document.querySelectorAll('.sqs-block-button a, .sqs-button-element--primary');

    buttons.forEach(function(button) {
      button.addEventListener('click', function(e) {
        var buttonText = this.textContent.trim();
        var buttonUrl = this.getAttribute('href');

        if (typeof gtag !== 'undefined') {
          gtag('event', 'button_click', {
            'button_text': buttonText,
            'button_url': buttonUrl,
            'page_location': window.location.pathname
          });
        }
      });
    });
  });
</script>

Video Engagement

For videos embedded via Squarespace's video blocks (YouTube, Vimeo):

YouTube Videos

Enhanced Measurement tracks YouTube engagement automatically, but for custom events:

<script>
  // Track YouTube video engagement
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  var players = [];

  function onYouTubeIframeAPIReady() {
    var videos = document.querySelectorAll('.sqs-video-wrapper iframe[src*="youtube.com"]');

    videos.forEach(function(video, index) {
      var player = new YT.Player(video, {
        events: {
          'onStateChange': function(event) {
            var videoData = event.target.getVideoData();

            if (event.data === YT.PlayerState.PLAYING) {
              if (typeof gtag !== 'undefined') {
                gtag('event', 'video_start', {
                  'video_title': videoData.title,
                  'video_provider': 'youtube'
                });
              }
            } else if (event.data === YT.PlayerState.ENDED) {
              if (typeof gtag !== 'undefined') {
                gtag('event', 'video_complete', {
                  'video_title': videoData.title,
                  'video_provider': 'youtube'
                });
              }
            }
          }
        }
      });
    });
  }
</script>

Track gallery image clicks and lightbox opens:

<script>
  document.addEventListener('DOMContentLoaded', function() {
    // Track gallery image clicks
    var galleryImages = document.querySelectorAll('.sqs-gallery-block-grid .image-slide-anchor');

    galleryImages.forEach(function(image, index) {
      image.addEventListener('click', function(e) {
        var imageAlt = this.querySelector('img') ? this.querySelector('img').getAttribute('alt') : '';

        if (typeof gtag !== 'undefined') {
          gtag('event', 'gallery_image_click', {
            'image_alt': imageAlt || 'Gallery Image ' + (index + 1),
            'gallery_location': window.location.pathname
          });
        }
      });
    });
  });
</script>

Ajax Cart Updates (Squarespace 7.1)

Squarespace 7.1 uses Ajax for cart updates. Track these without full page reloads:

<script>
  // Track cart quantity updates
  (function() {
    if (window.Y && window.Y.Squarespace) {
      window.Y.use(function(Y) {
        Y.on('cart:item:updated', function(e) {
          var item = e.item;

          if (typeof gtag !== 'undefined') {
            gtag('event', 'cart_quantity_update', {
              'item_id': item.id,
              'item_name': item.title,
              'new_quantity': item.quantity
            });
          }
        });
      });
    }
  })();
</script>

Custom Event Parameters

Add Squarespace-specific context to your events:

// Add to your event tracking code
gtag('event', 'your_event_name', {
  'squarespace_version': document.body.classList.contains('squarespace-7.1') ? '7.1' : '7.0',
  'template_name': getTemplateName(),
  'page_type': getPageType()
});

function getTemplateName() {
  // Extract template name from body class
  var bodyClasses = document.body.className;
  var templateMatch = bodyClasses.match(/template-([^\s]+)/);
  return templateMatch ? templateMatch[1] : 'unknown';
}

function getPageType() {
  if (window.location.pathname === '/') return 'homepage';
  if (window.location.pathname.includes('/blog/')) return 'blog_post';
  if (window.location.pathname.includes('/products/')) return 'product';
  if (window.location.pathname.includes('/checkout')) return 'checkout';
  return 'page';
}

Testing Your Events

1. Use GA4 DebugView

  1. Install Google Analytics Debugger
  2. Enable the extension
  3. Navigate to Configure > DebugView in GA4
  4. Trigger events on your site
  5. Verify events appear in DebugView with correct parameters

2. Real-Time Reports

  1. Go to Reports > Realtime in GA4
  2. Trigger your custom events
  3. Check that events appear in the event list

3. Browser Console

Add debug logging to your event code:

gtag('event', 'form_submit', {
  'form_name': 'contact_form'
});
console.log('GA4 Event Sent: form_submit');

Common Issues & Solutions

Events Not Firing

Possible Causes:

  • JavaScript errors preventing code execution
  • Events firing before gtag is loaded
  • Ad blockers blocking GA4

Solutions:

  1. Check browser console for errors
  2. Ensure gtag is loaded before custom events
  3. Test in incognito mode without ad blockers

Duplicate Events

Cause: Event listeners added multiple times or conflicting tracking methods

Solution:

  • Use event delegation instead of multiple listeners
  • Check for duplicate code in Code Injection sections
  • Remove conflicting GTM tags if using both methods

Events Missing Parameters

Cause: Data not available when event fires

Solution:

  • Add null checks before sending events
  • Use setTimeout to wait for data to load
  • Log data to console to verify it's available

Best Practices

  1. Use Consistent Naming:

    • Follow GA4 recommended event naming (lowercase, underscores)
    • Use standard eCommerce event names when applicable
  2. Add Meaningful Parameters:

    • Include context like page location, item details, etc.
    • Make events filterable and useful for analysis
  3. Test Thoroughly:

    • Test on desktop and mobile
    • Test with and without ad blockers
    • Verify all commerce scenarios (add, remove, checkout)
  4. Document Your Events:

    • Keep a list of custom events and their purposes
    • Document where tracking code is located
    • Note any dependencies or special configurations

Next Steps

// SYS.FOOTER