GTM and URL Hash Fragments

gtm-and-url-hash-fragments

If you’re trying to create a trigger in Google Tag Manager (GTM) that tracks a page with a hash (#) within the URL you might find it is not that easy, but you are in the right place.

Let’s say you want to create a trigger using a Regular Expression (RegEx) to match the URL /mystore/cart#/checkout. However, GTM’s “Page Path” variable doesn’t capture hash fragments (#). Instead, you need to use the “New History Fragment” variable.

In GTM, the “New History Fragment” is a built-in variable that captures changes in the URL hash (#) when using a History Change trigger. However, this variable is not enabled by default.

To enable the “New History Fragment” variable in GTM follow these steps:

1. Open GTM and go to the Variables section.
2. Scroll down to Built-in Variables and click Configure.
3. Find the History Variables section.
4. Check the box for New History Fragment.
5. Save the changes.

Once “New History Fragment” variable enabled, you can use it in a History Change trigger to detect when the URL changes to #/checkout.

Here’s how to use “New History Fragment” in a Trigger:

1. Go to Triggers → New.
2. Choose Trigger Type → History Change.
3. Under “This trigger fires on,” select Some History Changes.
4. Set the condition: New History FragmentMatches RegEx^/checkout$
5. Save the trigger.

The New History Fragment captures only the portion after #, making it ideal for SPAs (Single Page Applications) and checkout flows.

Now, when the URL changes from /mystore/cart#/checkout, the trigger will fire correctly.