Know if the page is in the background

Asked

Viewed 87 times

2

Is it possible to know if the page of my site is being visited in the background by the internet user? Is there any code or way to know?

  • In the background? what do you mean?

2 answers

4


The old way of doing this, which is also more compatible with older browsers, is like this:

var focused = true;
window.onfocus = function() {
    focused = true;
};
window.onblur = function() {
    focused = false;
};

and so at any time you can test if (focused) { and do something if it’s positive or negative.

You can combine that with document.hasFocus(); who basically does the same thing.

The way you expect it to be better, but it’s still a recommendation, although it’s being implemented in some browsers, is the Page Visibility which has new events and two new ways to check with static properties:

  • document.hidden, which may be true or false
  • document.visibilityState

Suggestion of polyfill

Here is a suggestion that seems to cover both cases of old browsers and also detects the new API I mentioned. This suggestion has a global focused which is updated with each status change and also a function that is run when the state changes. I tested it here and it worked as it should:

var focused = true; // sempre atualizada
function visibilityHandler(state) {
    console.log(state); // vai registando mudanças
}
(function(cb) {

    if (typeof document.hidden !== "undefined") {
        hidden = "hidden";
        visibilityChange = "visibilitychange";
    } else if (typeof document.mozHidden !== "undefined") {
        hidden = "mozHidden";
        visibilityChange = "mozvisibilitychange";
    } else if (typeof document.msHidden !== "undefined") {
        hidden = "msHidden";
        visibilityChange = "msvisibilitychange";
    } else if (typeof document.webkitHidden !== "undefined") {
        hidden = "webkitHidden";
        visibilityChange = "webkitvisibilitychange";
    }

    if (typeof document.addEventListener === "undefined" || typeof document[hidden] === "undefined") {
        window.onfocus = function() {
            focused = true;
            cb(focused);
        };
        window.onblur = function() {
            focused = false;
            cb(focused);
        };
    } else {
        document.addEventListener(visibilityChange, function() {
            focused = !focused;
            cb(focused);
        }, false);
    }
})(visibilityHandler);

jsFiddle: https://jsfiddle.net/n2wa92to/

  • If this is the old way, what would be the current way? (Curiosity)

  • 1

    @Fernando well seen, I forgot to add, I edited now.

  • 1

    @Fernando added another edition, now that the game of Portugal is already done.

  • Sergio, but how do I use this function? And just insert it and call it on my page and that’s it? I DON’T NEED TO MODIFY ANYTHING ELSE?

  • @valpmg or fez if (focused) { when you need to know, or put code that needs to run when the state changes within visibilityHandler.

1

I don’t know if the "present way" that the @Sergio mentioned is this, but you can use the Page Visibility API.

Not supported for all browsers, as shown in the table below:

inserir a descrição da imagem aqui

In the Developer. you own a usage tutorial (play video when the page is visible), and your live demo shows the operation.

The code of the demo example is this below:

   // Inline code is for educational purposes. Best practice is to put your scripts in external files.
    // Based on the tutorial at https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API

(function() {
    'use strict';

    // Set the name of the "hidden" property and the change event for visibility
    var hidden, visibilityChange; 
    if (typeof document.hidden !== "undefined") {
      hidden = "hidden";
      visibilityChange = "visibilitychange";
    } else if (typeof document.mozHidden !== "undefined") { // Firefox up to v17
      hidden = "mozHidden";
      visibilityChange = "mozvisibilitychange";
    } else if (typeof document.webkitHidden !== "undefined") { // Chrome up to v32, Android up to v4.4, Blackberry up to v10
      hidden = "webkitHidden";
      visibilityChange = "webkitvisibilitychange";
    }

    var videoElement = document.getElementById("videoElement");

    // If the page is hidden, pause the video;
    // if the page is shown, play the video
    function handleVisibilityChange() {
      if (document[hidden]) {
        videoElement.pause();
      } else {
        videoElement.play();
      }
    }

    // Warn if the browser doesn't support addEventListener or the Page Visibility API
    if (typeof document.addEventListener === "undefined" || typeof document[hidden] === "undefined") {
      alert("This demo requires a modern browser that supports the Page Visibility API.");
    } else {
      // Handle page visibility change   
      document.addEventListener(visibilityChange, handleVisibilityChange, false);

      // When the video pauses and plays, change the title.
      videoElement.addEventListener("pause", function(){
        document.title = 'Paused';
      }, false);

      videoElement.addEventListener("play", function(){
        document.title = 'Playing'
      }, false);
    }

})();

Just for knowledge, there are some projects for that purpose. What I know is the ifvisibility.

  • Thanks for the tip Randrade, I’ll take a look at the Veloper.Mozilla.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.