Using visibility API in Angular?

Issue

I have implemented Visibility API inside a constructor of an Angular component similar to this

constructor() {
    var hidden, state, visibilityChange;
    if (typeof document.hidden !== "undefined") {
        hidden = "hidden";
        visibilityChange = "visibilitychange";
        state = "visibilityState";
    }

    document.addEventListener(visibilityChange, function() {
        if(status == hidden){
            console.log("Hidden");
        }
        else if(status != hidden){
            console.log("Visible");
        }
    }, false);
}

pauseVideo(){
    //Video pause code
}

I need to pause the video i.e., call the pauseVideo() method when the Visibility changes to hidden, How do i do it?

Solution

I don’t know why you say document.hidden does not work in the event listener as it works just fine for me:

document.addEventListener(
  "visibilitychange"
  , () => { 
    if (document.hidden) { 
      console.log("document is hidden");
    }else{
      console.log("document is showing");
    }
  }
);

If you have an error of sorts could you open the dev tools (F12) and inspect the console? Maybe break on the error and see what’s wrong?

Answered By – HMR

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published