How to tell if browser/tab is active

JavascriptJquery

Javascript Problem Overview


> 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 :).

Javascript Solutions


Solution 1 - Javascript

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.

Learn more (2019 update)

Solution 2 - Javascript

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)

Solution 3 - Javascript

I would try to set a flag on the window.onfocus and window.onblur events.

The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:

var isTabActive;
 
window.onfocus = function () { 
  isTabActive = true; 
}; 

window.onblur = function () { 
  isTabActive = false; 
}; 
 
// test
setInterval(function () { 
  console.log(window.isTabActive ? 'active' : 'inactive'); 
}, 1000);

Try it out here.

Solution 4 - Javascript

Using jQuery:

$(function() {
	window.isActive = true;
	$(window).focus(function() { this.isActive = true; });
	$(window).blur(function() { this.isActive = false; });
	showIsActive();
});

function showIsActive()
{
	console.log(window.isActive)
	window.setTimeout("showIsActive()", 2000);
}

function doWork()
{
	if (window.isActive) { /* do CPU-intensive stuff */}
}

Solution 5 - Javascript

If you are trying to do something similar to the Google search page when open in Chrome, (where certain events are triggered when you 'focus' on the page), then the hover() event may help.

$(window).hover(function() {
// code here...
});

Solution 6 - Javascript

All of the examples here (with the exception of rockacola's) require that the user physically click on the window to define focus. This isn't ideal, so .hover() is the better choice:

$(window).hover(function(event) {
    if (event.fromElement) {
        console.log("inactive");
    } else {
        console.log("active");
    }
});

This'll tell you when the user has their mouse on the screen, though it still won't tell you if it's in the foreground with the user's mouse elsewhere.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionckknightView Question on Stackoverflow
Solution 1 - JavascriptgearsdigitalView Answer on Stackoverflow
Solution 2 - JavascriptRichard SimõesView Answer on Stackoverflow
Solution 3 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 4 - JavascriptChris FulstowView Answer on Stackoverflow
Solution 5 - JavascriptTrav LView Answer on Stackoverflow
Solution 6 - JavascriptDaniel QuinnView Answer on Stackoverflow