Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Using the PageVisibility API

Using the PageVisibility API

This is a quick intro to the PageVisibility API which landed in most of the current web browsers and enables some really nice features.

Given at http://berlinjs.org at 21st March 2013.

Robin Mehner

March 21, 2013
Tweet

More Decks by Robin Mehner

Other Decks in Technology

Transcript

  1. Using the PageVisibility API
    I can see hidden tabs.

    View Slide

  2. Robin Mehner
    @rmehner
    - running a small “agency” doing web development
    - Berlin.JS, up.front, BEPHPUG, Reject.js, NodeCopter bla bla bla

    View Slide

  3. What’s the PageVisibility API?
    With all the HTML5 JS posterchilds like Canvas, WebWorkers, FileReader and all the other stuff that you can use if you start your browser with 25 flags, it’s one of the most
    overlooked additions to our toolbelt

    View Slide

  4. Gives you an API to react on visibility changes of the tab
    document.hidden // boolean
    document.visibilityState // ‘hidden’, ‘visible’ or ‘prerender’
    ‘visibilitychange’ event

    View Slide

  5. Demo
    http://rmehner.github.com/page-visibility-api-demo

    View Slide

  6. spotify-remote
    https://github.com/rmehner/spotify-remote
    Stops polling when no client is connected (= reduced resource usage)

    View Slide

  7. stop animations
    stop video playback
    give the user a digest of the latest changes when he’s back
    stop polling
    pause/resume a game
    stop playing sounds (that annoying “which tab is playing sound?”)
    Use cases
    Not only for saving battery, but also for a lot of additional UX stuff

    View Slide

  8. Coming to your browser soon (currently implemented in Chrome Canary)

    View Slide

  9. Browser support is pretty good.
    There’s one (major) browser who does not support it in it’s current version ... Safari.
    http://caniuse.com/#feat=pagevisibility (Also the best site ever, since Amazing Horse.)

    View Slide

  10. Polyfills to the rescue!
    Modernizr Wiki: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills
    Using focusin/focusout/blur events as fallback

    View Slide

  11. Don’t be fooled by pagehide / pageshow
    Unless you know what you’re doing.
    Sound like the right deal, but they’re just onload / onunload with cache semantics. Different behaviour in iOS:
    * iPhone fires the event when the user switches the tab, iPad not
    * iOS stops execution of JS when you switch a tab
    * workaround with heartbeat

    View Slide

  12. http://coding-robin.de/2013/03/13/using-the-page-visibility-api.html

    View Slide

  13. Thanks.
    If I can do a talk, you can too!

    View Slide