1

Say I make a program and run it on chrome, then switch tabs.

Or what if I open my javascript app, then switch apps, while having mine in the background.

Is there way to tell if the program is on foreground or background in javascript?

Thanks, this would really help.

2 Answers 2

2

You can use Page Visibility API to handle foreground/background switch in Javascript.

if (document.visibilityState == "visible") {
    // foreground
} else if (document.visibilityState == "hidden" {
    // background
}

Checking for document.hasFocus() wouldn't work on cases when the page is running in foreground (and visible), but not focused.

Refer to https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState for details.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use document.hasFocus() to check if the current page is focused.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.