Skip to content

Analytics Magic

A resource for Google Analytics 4

  • Home
  • Setting up GA4 in polymer

Setting up GA4 in polymer

Setting up GA4 in a Polymer project involves a few processes.

Create a GA4 Property, if you haven’t done so here is the walkthrough on doing this. Once you are done with this, you will need to install the Google Analytics Web Component.

You can use a web component to easily add Google Analytics tracking to your Polymer application. Install the “google-analytics” component by running the following command in your terminal:

bower install --save GoogleWebComponents/google-analytics

This command installs the google-analytics component, which includes the necessary elements to add Google Analytics tracking to your Polymer application.

Import the Component: Import the Google Analytics component in your application. You can add the following line to your main index.html or any Polymer element that makes sense:

<link rel="import" href="/bower_components/google-analytics/google-analytics.html">

Add the GA4 Tracking Code: Add the google-analytics element to your application, using your GA4 Measurement ID:

<google-analytics id="analytics" tracking-id="G-XXXXXXXXXX"></google-analytics>

Track Page Views: To track page views, you need to send a page view hit whenever the route changes. This can be done by listening to the ‘location-changed’ event from the app-location element (if you’re using it), or your own custom routing solution. Here is an example:

<app-location route="{{route}}" on-location-changed="_trackPageview"></app-location>

<script>
  class MyApp extends Polymer.Element {
    // ...
    _trackPageview() {
      let ga = document.querySelector('#analytics');
      ga.send('pageview', {'page': window.location.pathname + window.location.search});
    }
  }
  customElements.define('my-app', MyApp);
</script>

Remember to replace G-XXXXXXXXXX with your actual Measurement ID from GA4. This will track a page view each time your route changes.

Track Events: If you want to track custom events, you can use the send method on the google-analytics element. Here’s an example:

<button on-click="_trackButtonClick">Click me</button>

<script>
  class MyApp extends Polymer.Element {
    // ...
    _trackButtonClick() {
      let ga = document.querySelector('#analytics');
      ga.send('event', {
        'eventCategory': 'button',
        'eventAction': 'click',
        'eventLabel': 'my-button'
      });
    }
  }
  customElements.define('my-app', MyApp);
</script>

This will send an event to GA4 every time the button is clicked.

This is a simple integration and you may need to adjust it based on your app’s requirements and structure. For more complex analytics, consider using Google Tag Manager or a dedicated JavaScript library.

Copyright © 2026 Analytics Magic.

Theme: Oceanly News Dark by ScriptsTown