Don't have one? Create one ↗
← All courses

Lesson 13 of 15

Tab Visibility

Intermediate

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
1

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.

2

Build it in GTM

  1. 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.

    1. Go to Tags → New and choose Custom HTML.
    2. Paste a script that listens for the browser's visibilitychange event and pushes { event: 'visibility_change', page_visible: document.visibilityState === 'visible' }.
    3. Set its firing trigger to All Pages, name it Listener - Visibility, and Save.
  2. Create the Custom Event trigger

    1. Go to Triggers → New and choose Custom Event.
    2. Set Event name to visibility_change (it must match the event you pushed).
    3. Name it Event - visibility_change and Save.
  3. Capture the state in a variable

    1. Go to Variables → New (under User-Defined Variables) and choose Data Layer Variable.
    2. Set Data Layer Variable Name to page_visible.
    3. Name it DLV - page_visible and Save.
  4. Attach a tag

    1. Go to Tags → New and choose Custom HTML with <script></script> (or your GA4 Event tag). Name it Custom HTML - Test.
    2. Under Triggering, add Event - visibility_change. If it's a GA4 tag, send DLV - page_visible as a parameter. Then Save.
3

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.

  1. In your GTM, click Preview.
  2. Paste the live page URL above and click Connect.
  3. Interact with the live page and watch your tags fire in Tag Assistant.

What you should expect to see

Each time you switch away and back, a visibility_change event appears in the timeline and dataLayer with page_visible true or false, and your tag fires.
0 of 15 lessons complete