Check out a free preview of the full JavaScript in the Background course

The "Visibility Change Detection" Lesson is part of the full, JavaScript in the Background course featured in this preview video. Here's what you'd learn in this lesson:

Maximiliano briefly discusses detecting the visibility state change with event listeners.

Preview
Close

Transcript from the "Visibility Change Detection" Lesson

[00:00:00]
>> So, that means that on all platforms, the code that I will show you will actually show you all the options. Like when the user is going from running to post, to post, to running or running active to running inactive, it doesn't matter, its the same code. We shall listen for visibility change on the window object I'm going to show you that in actually a minute, and then we check the visibility state on the document.

[00:00:27]
If it's hidden, it's because we are going into the background. Which of the options for the background? We don't know. It's the background tab, is the background window, it's the user closing the whole browser. We actually don't know, okay. And as I mentioned before, on some devices that's the moment to save the state, okay.

[00:00:51]
If you're using something like Redux or a state manager, maybe that's a moment to actually save that safely somewhere. Locally, that's better. Because if you want to send that to the server, you don't know on mobile if you have enough time to send that to the server. So if you're trying to send that to the server and iOS, and it's taking more than two seconds, your request will probably be aborted.

[00:01:18]
So you will never get that server side.
>> What are the other values for visibility state?
>> Visible, okay. And then you can also mix that with with other properties for example you can know if it's visible and focused. Because mostly on desktop, but now on iPad and Android, you can also have two apps at the same time.

[00:01:43]
So both are visible, but only one is the one in focus. So you can also detect that if you want to. But for background execution, yeah, maybe we don't get too much if it's the focus one or not, okay? If it's visible, the user is actually seeing the app.

[00:01:57]
So it's probably expecting the web app to react as if it's the one that is there. It should be live.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now