Tracking Dark and Light Mode in Google Analytics using Google Tag Manager

Submitted by david.stinemetze on Thu, 12/05/2019 @ 2:23pm

With both macOS and Windows on desktop, along with iOS and Android on mobile, supporting dark mode, we wanted to see if we could track audience color preferences in Google Analytics. This is useful as it could impact design decisions down the road, and determine whether or not it's worth creating a dark version of a website.

As it turns out, prefers-color-scheme can be used to do so. While not supported by every browser, it seems to work in most modern browsers, which is good enough for my purposes. As it turns out it's pretty easy to pull this off in Google Tag Manager (GTM).

Creating a Color Mode Variable

According to the prefers-color-scheme spec, a user could have one of the following values:

  • dark
  • light
  • no-preference

As such, we want to be able to identify all three, so we created a new Custom Javascript variable called "User - Color Mode":

Screenshot of the new Color Mode variable.

function () {
  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    return 'Dark';
  }
  else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
    return 'Light';
  }
  return 'No Preference';
}

FYI, I am conflating "No Preference" with browsers that just don't flat out support prefers-color-scheme here. In my mind, they're kind of the same thing. If you need more granularity here, you could create a separate condition for that.

Creating a Color Mode Tag

I then created a new Google Analytics: Universal Analytics tag:

Screenshot of the new Color Mode tag.

These are the important settings needed to get it working:

  • Category: User
  • Action: Color Mode
  • Label: {{ User - Color Mode }}
  • Non-interaction hit: True
  • Tag firing options: Once per page
  • Firing trigger: DOM Ready

Verifying the Tags

Using GTM preview mode, I'm able to test this out when I toggle my OS settings.

Dark Mode

Here we can see the label value is set to "Dark":

Preview Mode in Dark Mode

Light Mode

Here we can see the label value is set to "Light":

Preview Mode in Light Mode

Seeing the data in Google Analytics

I'm now able to start seeing data in Google Analytics.

Screenshot of Color Mode data in Google Analytics

Disclaimer: this screenshot is from another website I work on with way more traffic than my blog.