how to know what caused visibilitychange

Viewed 155

I am using visibilitychange event of the browser. The website is for mobiles. So I test it from my mobile.

document.addEventListener('visibilitychange', (e) => {
    console.log("visibility changed", e);
})

This could be caused by many different things.

  • switching apps back and forth
  • force-closing app
  • when the screen turns off

Is there any way to detect what behaviour caused visibilitychange listener to get called? I tried e.target and e.srcElement, but in all cases, they seem to be the same. Any ideas?

1 Answers

Short answer: you can't

As stated in the MDN documentation for the visibilitychange event:

The visibilitychange event is fired at the document when the content of its tab have become visible or have been hidden.

You only have two value possible, visible or hidden. That's all the website can know. You are asking a web browser to have acute knowledge of what the user is doing on his operating system (did he locked his computer? did he switch to a new app? did he kill the web browser?) which is privacy wise, not very useful nor safe.

However if you absolutely need these features and can afford to make the user install your app, you could use something like cordova.

Related