locked
How to tell when application not visible anymore?

    Question

  • Hi everyone,

     We are wondering how you can tell in a Metro JS application, that the application has been minimized, and is no longer visible on the users screen?

    We would like to use this event to "pause" an action game so that the user can resume when they return without losing any time in the game.

    We found that the suspend lifecycle event only triggers after a few seconds of the app being minimized, but this is not good enough because we need to pause the game timer immediately.

    We found that the onfocusout event works decently, but also triggers if you change your app from fullscreen to snap view, but we only want to pause the second the app is no longer visible on the screen.

    Any suggestions?

    Thanks!

    Wednesday, May 9, 2012 11:22 PM

Answers

  • In addition to the HTML blur event, which handles focus, you can also use the msvisibilitychange event (http://msdn.microsoft.com/en-us/library/windows/apps/hh441213.aspx). I've used blur for a game with a timer successfully since it could still be visible and playable but not focused (e.g. snapped and the user is interacting with the filled app, in which case the snapped app won't get a visibility change event).
    • Marked as answer by Michael Nehls Thursday, May 10, 2012 3:40 AM
    Thursday, May 10, 2012 1:28 AM

All replies

  • In addition to the HTML blur event, which handles focus, you can also use the msvisibilitychange event (http://msdn.microsoft.com/en-us/library/windows/apps/hh441213.aspx). I've used blur for a game with a timer successfully since it could still be visible and playable but not focused (e.g. snapped and the user is interacting with the filled app, in which case the snapped app won't get a visibility change event).
    • Marked as answer by Michael Nehls Thursday, May 10, 2012 3:40 AM
    Thursday, May 10, 2012 1:28 AM
  • Thanks, this is exactly the info we needed!
    Thursday, May 10, 2012 3:41 AM
  • Here's a post with a code sample that works in Windows 8 RP
    Monday, July 30, 2012 12:29 PM
  • The following code did the trick for me:

    document.addEventListener("msvisibilitychange",
        function(){
            if(document.msVisibilityState=="hidden"){
                //do something
            }else{
                //do something else
            }
        },false
    );

    Sunday, August 19, 2012 9:12 PM
  • Kraig, how did you register your blur timer? On the document I tried but it was never fired.
    Friday, February 8, 2013 2:56 PM
  • Listen on the window object, e.g. window.onblur or window.addEventListener("blur"...). It won't work on the document object.

    Kraig

    Author, Programming Windows 8 Apps with HTML, CSS, and JavaScript, a free ebook from Microsoft Press


    Saturday, February 9, 2013 4:15 AM