Home » Track ‘Dark Theme’ in Google Analytics 4 (GA4 and GTM)

Track ‘Dark Theme’ in Google Analytics 4 (GA4 and GTM)

  • by
  • 2 min read

In this blog post, we’ll use media queries particular user (device) properties using Google Tag Manager and Google Analytics 4. Some JavaScript knowledge is not a luxury.

Using media queries, developers can personalize their app or website based on device and personal preferences by the user. Using the matchMedia method on the window object, one can check for particular properties.

Within a digital analytics context, there are various reasons why this can be interesting.

  1. Given particular settings, specific behavior and interaction with an app or website might be different. If the growth team wants to optimize a digital product for all devices and settings, media queries are a convenient way to track a device’s settings.
  2. Fingerprinting: by combining media queries and typical JavaScript variables within the window and document objects, it’s quite easy to put together a quasi-unique user ID.

In this example, we want to track if a user has opted in for a dark themed experience on their device within Google Analytics 4. We will use Google Tag Manager to set up the tracking.

Take the following steps.

Go to Google Tag Manager > Variables > New > Custom JavaScript. Give the variable a suitable name, like ‘Dark Theme’ (duh). Paste the following code in the GTM variable editor:

function() {
  isDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
  return (isDark ? 'Dark Theme' : 'Light Theme');
}

Next, go to Tags, and select the GA4 event tag for which you’d like to know if it happens on a device with a dark theme preference.

There are multiple good reasons to tracking this information as an event parameter. However, if you expect your users to visit your website from one device, a user property is also valid. Adding it to a particular tag can be done as follows:

Great success!

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

Leave a Reply

Your email address will not be published. Required fields are marked *