Event for when user switches browser tabs

Asked
Active3 hr before
Viewed126 times

7 Answers

event
90%

The page's content is not visible to the user, either due to the document's tab being in the background or part of a window that is minimized, or because the device's screen is off.,The example, which pauses the video when you switch to another tab and plays again when you return to its tab, was created with the following code:,Note: While onblur and onfocus will tell you if the user switches windows, it doesn't necessarily mean it's hidden. Pages only become hidden when the user switches tabs or minimizes the browser window containing the tab.,Visibility states of an <iframe> are the same as the parent document. Hiding an <iframe> using CSS properties (such as display: none;) doesn't trigger visibility events or change the state of the document contained within the frame.

// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
   hidden = "hidden";
   visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
   hidden = "msHidden";
   visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
   hidden = "webkitHidden";
   visibilityChange = "webkitvisibilitychange";
}

var videoElement = document.getElementById("videoElement");

// If the page is hidden, pause the video;
// if the page is shown, play the video
function handleVisibilityChange() {
   if (document[hidden]) {
      videoElement.pause();
   } else {
      videoElement.play();
   }
}

// Warn if the browser doesn't support addEventListener or the Page Visibility API
if (typeof document.addEventListener === "undefined" || hidden === undefined) {
   console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
   // Handle page visibility change
   document.addEventListener(visibilityChange, handleVisibilityChange, false);

   // When the video pauses, set the title.
   // This shows the paused
   videoElement.addEventListener("pause", function() {
      document.title = 'Paused';
   }, false);

   // When the video plays, set the title.
   videoElement.addEventListener("play", function() {
      document.title = 'Playing';
   }, false);

}
load more v
88%

You might try using a framework, such as MooTools or jQuery which provide cross-browser support. They should be able to detect with more reliability the blur and focus events for the browser window., Quitting before the start date: is the non compete enforceable? ,Please be sure to answer the question. Provide details and share your research!,I personally have used jQuery with much success:

I personally have used jQuery with much success:

$(window).blur(function(e) {
   // Do Blur Actions Here
});
$(window).focus(function(e) {
   // Do Focus Actions Here
});
load more v
72%

We’re going to use an event called visibilitychange. Then provide a callback function which will change the document title of the page with the value of the visibilityState property whenever the visibility changes on the web page.,As you can see, the tab title on top change to hidden when you change to another tab and change to visible when change back to the page.,So that’s how to use the visibility API in JavaScript.,In the script tag, we’re going to add an event listener to the document object.

In the script tag, we’re going to add an event listener to the document object.

document.addEventListener('visibilitychange', function() document.title = document.visibilityState; console.log(document.visibilityState);
});
65%

The blur event is triggered when an element or the entire tab (document) loses focus, i.e. when we no longer access it. In contrast, the focus event is triggered when an element or the tab (document) is refocused, i.e. in our case it is back on the tab.,We register the blur event on the global document variable. Generally, the blur and focus events are often used in conjunction.,This website uses cookies to personalize content and advertisements and to track your visit. This allows us to further improve the user experience for this website in the future., Save my name, email, and website in this browser for the next time I comment.

The blur event is triggered when an element or the entire tab (document) loses focus, i.e. when we no longer access it. In contrast, the focus event is triggered when an element or the tab (document) is refocused, i.e. in our case it is back on the tab.

// user leaves the tab
document.addEventListener('blur', (e) => {
   // your custom code here
});

// user enters the tab (again)
document.addEventListener('focus', (e) => {
   // your custom code here
});
load more v
75%

This method works for detecting both when a tab is being closed or when the browser is being closed.,A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.,How to close current tab in a browser window using JavaScript?,How to detect browser or tab closing in JavaScript ?

Syntax:

window.addEventListener('beforeunload', function(e) {
   e.preventDefault();
   e.returnValue = '';
});
load more v
40%

I'm looking for an event which will fire whenever the user switches away from the page to another tab, and another event which fires when the user switches back to the tab again.,Is there a proxy I could look at in order to synthesize this event?,You might try using a framework, such as MooTools or jQuery which provide cross-browser support. They should be able to detect with more reliability the blur and focus events for the browser window.,I personally have used jQuery with much success:

I personally have used jQuery with much success:

$(window).blur(function(e) {
   // Do Blur Actions Here
});
$(window).focus(function(e) {
   // Do Focus Actions Here
});
load more v
22%

Or you want to run the Animation only when the user is active otherwise stop it.,If you want to know How much time the user active on your website, in this case, you can use JavaScript. Using that you only enabled the timer when the user is an active tab on your website.,focus  – for detecting active state, when this event trigger I start the timer,blur – for detecting inactive, state. From where I stop the timer by clearing the Interval.

Completed Code

<div class='container'>
 Seconds : <div id='seconds'></div>
</div>

<!-- Script -->
<script type='text/javascript'>
 
 var count = 0;
 var myInterval;
 // Active
 window.addEventListener('focus', startTimer);

 // Inactive
 window.addEventListener('blur', stopTimer);

 function timerHandler() {
  count++;
  document.getElementById("seconds").innerHTML = count;
 }

 // Start timer
 function startTimer() {
  console.log('focus');
  myInterval = window.setInterval(timerHandler, 1000);
 }

 // Stop timer
 function stopTimer() {
  window.clearInterval(myInterval);
 }
</script>

Other "event-undefined" queries related to "Event for when user switches browser tabs"