How to track Scroll-to-text fragments in Google Analytics 4 with GTM
Justus
owntag Founder
published May 12, 2021
The difficult questions are the interesting ones and the answers to them are often hard to find. To make it a little easier, Google now uses Scroll To Text Fragments in their search results. Most notably in Featured Snippets, the boxes that highlight the answer to your query:
The target of this link looks like this:
The #:~:text=
part signals the scroll-to-text fragment to the browser and will scroll to the relevant text section on the page and highlight it:
Unfortunately, Google has stopped showing data about those fragments in Google Search Console in May 2021. If you track the content of the fragment in Google Analytics, you can at least retain some insight into which sections of your pages are the most highlighted.
With Google Tag Manager
Step 1: Create a fragment variable
Create a Custom JavaScript variable that extracts the fragment from the user’s URL. You can simply copy & paste the following:
function test() {
if (performance && performance.getEntries()[0].name.indexOf("#:~:text=") != -1)Â {
var entries = decodeURIComponent(performance.getEntries()[0].name.match("#:~:text=(.*)")[1]);
var frag = entries.replace(/, /g,"*").replace(/,/g,"...").replace(/\*/g,", ");
return frag;
}
else return ""
}
I’ll call this one js.fragment
.
Step 2: Add the parameter to GA4
Since you’re reading this fairly specific article, I’m going to assume you already have a basic GA4 setup up and running. If not, check out Simo Ahava’s guide to GA4 tracking first.
In your config or pageview tag for GA4, add a parameter of your own choosing and set its value to reference the {{js.fragment}}
variable you created one step earlier:
Then you can publish your Google Tag Manager container and you should already be sending the fragments to your GA4 property.
Create the dimension in GA4
To actually conveniently access the data in GA4, you should then create a custom dimension based on the new parameter. Scroll down in the left navigation to find your Custom Definitions and create a new dimension:
Keep in mind that the Event parameter field should match with the parameter name in your GA4 tag in GTM. Here, that’s scroll_to_text
:
And that’s it, you can now include your know Scroll To Text Fragment dimension in your Google Analytics 4 reports.
Become a Server Side Tagging Pro with owntag
Take control of your digital data collection with Server Side Tagging and Server Side GTM – easily hosted with owntag.