Lesson 13 of 15
Tab Visibility
Track when a visitor switches away and returns using the Page Visibility API.
① Connect your GTM container
Paste your container ID to load it into this page. It only ever runs here.
Advanced: use a specific environment
Goal
Track when a visitor backgrounds the tab and returns, using the Page Visibility API. Push visibility_change with the new state.
- Switch to another tab and come back
Listen for visibilitychange and read document.visibilityState.
Build it in GTM
Add the visibility listener
GTM has no built-in tab-visibility trigger, so a small Custom HTML tag does the listening and pushes its own event.
- Go to Tags → New and choose Custom HTML.
- Paste a script that listens for the browser's
visibilitychangeevent and pushes{ event: 'visibility_change', page_visible: document.visibilityState === 'visible' }. - Set its firing trigger to All Pages, name it
Listener - Visibility, and Save.
Create the Custom Event trigger
- Go to Triggers → New and choose Custom Event.
- Set Event name to
visibility_change(it must match theeventyou pushed). - Name it
Event - visibility_changeand Save.
Capture the state in a variable
- Go to Variables → New (under User-Defined Variables) and choose Data Layer Variable.
- Set Data Layer Variable Name to
page_visible. - Name it
DLV - page_visibleand Save.
Attach a tag
- Go to Tags → New and choose Custom HTML with
<script></script>(or your GA4 Event tag). Name itCustom HTML - Test. - Under Triggering, add
Event - visibility_change. If it's a GA4 tag, sendDLV - page_visibleas a parameter. Then Save.
- Go to Tags → New and choose Custom HTML with
Debug in Tag Assistant
Open the live version of this lesson, that is the page you point Tag Assistant at. It has the clickable elements next to a live dataLayer, so this page stays clean for reading.
- In your GTM, click Preview.
- Paste the live page URL above and click Connect.
- Interact with the live page and watch your tags fire in Tag Assistant.
What you should expect to see
visibility_change event appears in the timeline and dataLayer with page_visible true or false, and your tag fires.