简体   繁体   中英

How can I detect when user switches the tab using javascript?

I want to end the fullscreen mode when the tab is changed or quickly switched. Is it possible to do it with javascript?

I have the following javascript code which ends fullscreen I want help in detecting the change in inter chrome tabs [using ctrl + tab shortcut] also in detecting the change in windows tabs like when a person switch chrome(any browser) to file explorer (for example)[using alt + tab shortcut].

My javascript code --

if (document.exitFullscreen) {
  document.exitFullscreen();
} 
else if (document.mozCancelFullScreen) {
  document.mozCancelFullScreen();
} 
else if (document.webkitExitFullscreen) {
  document.webkitExitFullscreen();
} 
else if (document.msExitFullscreen) {
  document.msExitFullscreen();
}

I want to wrap this code in the switch tab function. Please help.

I also tried -

document.addEventListener("visibilitychange", function tabsswitch() {
   if(document.hidden) {
     alert('document hidden')
   } 
});

but that's not working when i change the windows tab for instance like i switch from chrome to my code editor and again back to chrome it does't show any alert.

There is HTML 5 API to detect if tab visibility is changed:

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

The Page Visibility API provides us with two top-level attributes: document.hidden (boolean) and document.visibilityState (which could be any of these strings: “hidden”, “visible”, “prerender”, “unloaded”).

This would not be not good enough without an event we could listen to though, that's why the API also provides the useful visibilitychange event.

So, here's a basic example of how we could take action on a visibility change:

function handleVisibilityChange() {
  if(document.hidden) {
    // the page is hidden
  } else {
   // the page is visible
  }
}

document.addEventListener("visibilitychange", handleVisibilityChange, false);

Reference

I got similar issue, while using FullScreen mode tab visibility wasn't working. To detect the visibility while using alt + tab add this to existing code

window.addEventListener('focus', function() {
  console.log('show');
}, false);
window.addEventListener('blur', function() {
   console.log('hide');
}, false);

this worked for me! Hope this will be useful to detect the tab change in full screen and while using alt + tab

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