visibilitychange: Ever wondered how your browser knows when you leave a tab?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MyrinNew
    Senior Member
    • Feb 2024
    • 5175

    #1

    visibilitychange: Ever wondered how your browser knows when you leave a tab?

    Have you ever noticed how when you switch to another tab, the video or animation you were watching suddenly pauses, and when you come back - it resumes automatically? Or how some pages seem to pause their activity the moment you move away, and pick up right where they left off when you return?


    That’s all because of the Page Visibility API - specifically, the visibilitychange event. This simple event lets a web page know when it’s visible to the user or hidden in the background, so it can act smarter - like saving battery, pausing timers, or deferring background tasks until you return.


    Here’s the simplest possible example that shows exactly how it works 👇










    Tab Visibility Demo


    Switch tabs to see the magic ✨












    ✅ How to try it:

    1. Copy this into a file like tab-visibility.html.
    2. Open it in your browser.
    3. Open DevTools (F12 → Console).
    4. Switch to another tab → “👋 You left the tab!”
    5. Come back → “👀 Welcome back!”


    React version (just as easy)





    import { useEffect } from 'react';

    export default function App() {
    useEffect(() => {
    function handleVisibility() {
    if (document.hidden) {
    console.log('👋 You left the tab!');
    } else {
    console.log('👀 Welcome back!');
    }
    }

    document.addEventListener('visibilitychange', handleVisibility);
    return () => document.removeEventListener('visibilitychange', handleVisibility);
    }, []);

    return Switch tabs and check your console 👀

    ;
    }








    This tiny event is behind so much of what makes the web feel smooth - from pausing media and animations to keeping your apps efficient and responsive. And the best part? It only takes a few lines of JavaScript!




    More...
Working...