How can I detect if a user is switching to another browser tab?
Currently, I have this:
$(window).on("blur focus", function (e) { var prevType = $(this).data("prevType"); if (prevType != e.type) { // reduce double fire issues switch (e.type) { case "blur": $('.message').html('<div class="alert alert-error">Oops. You navigated away from the ads <a id="start" class="butt green">Resume</a></div>'); var myDiv = $("#bar"); myDiv.clearQueue(); myDiv.stop(); clearInterval($timer); $timer = null; break; case "focus": // do work break; } } $(this).data("prevType", e.type); });
But that only works when the user is minimizing the active window.
To detect if user changes tab with JavaScript, we can listen to the visibilitychange event on document . We call document. addEventListener window 'visibilitychange' to listen to the visibilitychange event. In the event handler, we check if document.
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.
To check if the browser tab has focus using React:Add event listeners for the focus and blur events. If the focus event gets triggered, the tab has focus. If the blur event gets triggered, the tab has lost focus.
On every other page navigation in that same tab window.name is preserved. If you open a tab however, window.name is lost. At that point your script checks if the window.name is not blank, and because you're not on your first entry page, you've detected a new tab opened. Very neat!
Now we can use the visibility API.
To deal with the different browser-specific syntaxes, I made this small code :
var vis = (function(){ var stateKey, eventKey, keys = { hidden: "visibilitychange", webkitHidden: "webkitvisibilitychange", mozHidden: "mozvisibilitychange", msHidden: "msvisibilitychange" }; for (stateKey in keys) { if (stateKey in document) { eventKey = keys[stateKey]; break; } } return function(c) { if (c) document.addEventListener(eventKey, c); return !document[stateKey]; } })();
Usage :
var visible = vis(); // gives current state vis(aFunction); // registers a handler for visibility changes
Example :
vis(function(){ document.title = vis() ? 'Visible' : 'Not visible'; });
Demonstration page
These 3 lines of code worked for me
document.addEventListener("visibilitychange", function() { document.title = document.hidden ? "I'm away" : "I'm here"; });
reference link: document.hidden
demo: https://iamsahilralkar.github.io/document-hidden-demo/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With