Possible Duplicate:
Is there a way to detect if a browser window is not currently active?
I have a function that is called every second that I only want to run if the current page is in the foreground, i.e. the user hasn't minimized the browser or switched to another tab. It serves no purpose if the user isn't looking at it and is potentially CPU-intensive, so I don't want to just waste cycles in the background.
Does anyone know how to tell this in JavaScript?
Note: I use jQuery, so if your answer uses that, that's fine :).
$(window). hover(function(event) { if (event. fromElement) { console. log("inactive"); } else { console.
Use the visibilitychange event to detect if a browser tab has focus or not, e.g. document. addEventListener('visibilitychange', checkTabFocused) . The event is fired at the document when the contents of its tab have become visible or have been hidden.
Start by opening the Settings app and then, go to Update & Security. On the left side of the window, click or tap Activation. Then, look on the right side, and you should see the activation status of your Windows 10 computer or device.
In addition to Richard Simões answer you can also use the Page Visibility API.
if (!document.hidden) { // do what you need }
This specification defines a means for site developers to programmatically determine the current visibility state of the page in order to develop power and CPU efficient web applications.
document.hidden
You would use the focus
and blur
events of the window:
var interval_id; $(window).focus(function() { if (!interval_id) interval_id = setInterval(hard_work, 1000); }); $(window).blur(function() { clearInterval(interval_id); interval_id = 0; });
To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:
$(window).on("blur focus", function(e) { var prevType = $(this).data("prevType"); if (prevType != e.type) { // reduce double fire issues switch (e.type) { case "blur": // do work break; case "focus": // do work break; } } $(this).data("prevType", e.type); })
Click to view Example Code Showing it working (JSFiddle)
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