简体   繁体   中英

How can I check if browser tab is active and visible?

I am making website with contests and I want to check, if user's tab in browser is active and visible. For example, if person hides browser window or switches tab with my website, the tab won't be active and I need to know it. Can i do this or something like this?

I know about Firefox visibility API, but it checks only visibility. So, if there are two windows on the screen and one of them is browser window with website, website is visible. But other window can be active and my website will be visible, but not active. It It isn't something that I want

try:

document.addEventListener("visibilitychange", function() {
  console.log( document.hidden );  
});

window.addEventListener('focus', function() {
 console.log("window is active!" );
});

window.addEventListener('blur', function() {
  console.warn("window is not active!" );
});

Ok, it seems that I need to use document.hasFocus() ( docs ) js function. It returns false if tab isn't visible or other window is active, else it returns true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM