Assafi Cohen-Arazi
Assafi Cohen-Arazi

Reputation: 847

Program In Background Javascript

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.

Upvotes: 1

Views: 68

Answers (2)

subwaymatch
subwaymatch

Reputation: 1040

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.

Upvotes: 2

Freyja
Freyja

Reputation: 40924

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

Upvotes: 2

Related Questions