Statistics Dark Mode with Google Analytics

Original link: https://www.williamlong.info/archives/6916.html

At present, the mainstream operating systems (Windows, mscOS, iOS, and Android) all support dark mode, and many websites also support dark mode by modifying the code. Then, how do we count how many people are using dark mode in Google Analytics? , I will introduce the specific statistical methods below.

Count the dark and light modes by means of event statistics, set an event name, and the value inside is the dark and light code. The calling method of the event in Google Analytics UA is as follows.

ga(‘send’, ‘event’, [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);

Edit the Google Analytics statistics code in the global Javascript file of the website and modify the code as follows:

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’;

}

var dimensionValue = darkmode();

(function(i,s,o,g,r,a,m){i[‘GoogleAnalyticsObject’]=r;i[r]=i[r]||function(){

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)

})(window,document,’script’,’https://ift.tt/MAQKOJT);

ga(‘create’, ‘UA-XXXXX-Y’, ‘auto’);

ga(‘send’, ‘pageview’);

ga(‘send’, ‘event’,’darkmode’, dimensionValue);

After the code is released, after a while, the data can be viewed in Google Analytics.

The specific viewing positions are in: “Real Time” – “Event”, and “Behavior” – “Event”.

The above code modifications only apply to the Google Universal Analytics statistical code.

For the new version of Google Analytics 4 statistical code, the event statistical code is modified to the following code.

gtag(‘event’, <action>, {

‘event_category’: <category>,

‘event_label’: <label>,

‘value’: <value>

});

Therefore, for GA4, other codes remain unchanged, and the code for sending events can be modified as follows.

gtag(‘event’, dimensionValue, {‘event_category’: ‘darkmode’});

This article is reprinted from: https://www.williamlong.info/archives/6916.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment