13

Is there any way to detect that the window is currently active (is being shown on active tab/window) in IE8?

I know there are events like onfocusin/onfocus - but this is not a perfect solution, since the window must also receive focus for the event to be fired - so this does not work when the user just switches the tabs without touching the window itself.

I believe there has to be some simple, elegant solution for such ordinary use-case.

BiscuitBaker
  • 1,421
  • 3
  • 23
  • 37
Martin Bencik
  • 131
  • 1
  • 1
  • 4
  • The best way to do this is by using the Page Visibility API. However, this API is not available in older browsers. I’ve written a jQuery plugin that uses the best API available to detect if the page is visible or not: http://stackoverflow.com/a/9634295/96656 – Mathias Bynens Mar 09 '12 at 13:13

7 Answers7

16

I’ve written a jQuery plugin that does this: http://mths.be/visibility It gives you a very simple API that allows you to execute callbacks when the page’s visibility state changes.

It does so by using the the Page Visibility API where it’s supported, and falling back to good old focus and blur in older browsers.

Demo: http://mathiasbynens.be/demo/jquery-visibility

This plugin simply provides two custom events for you to use: show and hide. When the page visibility state changes, the appropriate event will be triggered.

You can use them separately:

$(document).on('show', function() {
  // the page gained visibility
});

…and…

$(document).on('hide', function() {
  // the page was hidden
});

Since most of the time you’ll need both events, your best option is to use an events map. This way, you can bind both event handlers in one go:

$(document).on({
  'show': function() {
    console.log('The page gained visibility; the `show` event was triggered.');
  },
  'hide': function() {
    console.log('The page lost visibility; the `hide` event was triggered.');
  }
});

The plugin will detect if the Page Visibility API is natively supported in the browser or not, and expose this information as a boolean (true/false) in $.support.pageVisibility:

if ($.support.pageVisibility) {
  // Page Visibility is natively supported in this browser
}
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
  • Thanks for your answer. I checked the web and it seems that Page Visibility API is included in IE10. It seems that for older versions, we have to stick to good-old-not-very-well-working blur/focus :) – Martin Bencik Mar 09 '12 at 13:56
  • 2
    Also this is not working if user switches another program when on your page. Just works with switching between tabs. – xecute Apr 01 '13 at 13:59
  • For a plugin that is cross-browser and deals with "issues" that arise using `.blur|.focus`, try checking out the answer here -> [Is there a way to detect if a browser window is not currently active?](http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active#answer-16043687) – SpYk3HH Dec 02 '13 at 18:46
  • @SpYk3HH The above plugin is cross-browser compatible and doesn’t have any known false positives. Do you know of any bugs in my plugin? If so, please report them. – Mathias Bynens Dec 03 '13 at 11:43
  • My bad. I thought I noticed use of `blur` and `focus`, and yes, you'll have issues with those 2. Aside from dealing with possible "double fire" that tends to happen with focus, those methods alone end up in non-positive reactions when simply clicking another program into focus. However, I haven't fully tested yours. I'll do that now. As for @xecute comment, it shouldn't blur when bringing another prog to focus. What if you blur hides values on a page and you need to use calculator? – SpYk3HH Dec 03 '13 at 13:36
  • @MathiasBynens This looks great -- I'd like to give it a try. I see it uses an event model; is it possible to simply check the current visibility status when another event happens? I have a chat feature that I'd like to have play a sound when a new message comes in, only when the application window is not visible. Thanks! – Tony Zito Dec 30 '14 at 21:25
  • 1
    I was really hopeful this would work for my use case. Unfortunately the demo at https://mathiasbynens.be/demo/jquery-visibility only works when switching between tabs in the same browser window, not to other browser windows or other programs. Confirmed in Chrome 73.0.3683.103 (Official Build) (64-bit) and Firefox 66.0.3 (64-bit) on Windows. – kevinmicke May 08 '19 at 16:05
2
document.addEventListener("visibilitychange", () => { 
    if (document.visibilityState === 'visible') alert("Hello again"); 
});

See Page Visibility API on MDN for more information.

Hauke
  • 451
  • 3
  • 11
  • See also: [visibilityState on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState). – Ed Lucas May 07 '21 at 16:45
2

Using the browser default Page Visibility API.

function isPageHidden(){
    if (typeof(document.hidden) === 'boolean') return document.hidden;
    if (typeof(document.msHidden) === 'boolean') return document.msHidden;
    if (typeof(document.webkitHidden) === 'boolean') return document.webkitHidden;
    if (typeof(document.mozHidden) === 'boolean') return document.mozHidden;
    else return undefined;
}
Silver Ringvee
  • 5,037
  • 5
  • 28
  • 46
2

var isActive = false;
function onBlur() {
    isActive = false;
};
function onFocus(){
    isActive = true;
};

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0
<script>

    // Adapted slightly from Sam Dutton
    // Set name of hidden property and visibility change event
    // since some browsers only offer vendor-prefixed support
    var hidden, state, visibilityChange; 
    if (typeof document.hidden !== "undefined") {
        hidden = "hidden";
        visibilityChange = "visibilitychange";
        state = "visibilityState";
    } else if (typeof document.mozHidden !== "undefined") {
        hidden = "mozHidden";
        visibilityChange = "mozvisibilitychange";
        state = "mozVisibilityState";
    } else if (typeof document.msHidden !== "undefined") {
        hidden = "msHidden";
        visibilityChange = "msvisibilitychange";
        state = "msVisibilityState";
    } else if (typeof document.webkitHidden !== "undefined") {
        hidden = "webkitHidden";
        visibilityChange = "webkitvisibilitychange";
        state = "webkitVisibilityState";
    }
    // Add a listener that constantly changes the title
    document.addEventListener(visibilityChange, function() {
        document.title = document[state];
    }, false);

    // Set the initial value
    document.title = document[state];

</script>
0

To check window is currently active or not use:

document.hasFocus();

It will return true if window is currently active, otherwise false.

To check window is currently visible or not use:

document.visibilityState;

It has two state, visible and invisible.

Al Sayeed
  • 65
  • 7
0

This is a simple task to achieve using jQuery:

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

The global isActive variable determines wether the tab/window is acive.

Community
  • 1
  • 1
Zar
  • 6,786
  • 8
  • 54
  • 76
  • Unfortunately, it’s not that simple. Try this in IE — the event handler will be called for every click on the document, which is not very efficient. See [my answer](http://stackoverflow.com/a/9634295/96656) for an optimized solution. – Mathias Bynens Mar 09 '12 at 12:51
  • For a plugin that is cross-browser and deals with "issues" that arise using `.blur|.focus`, try checking out the answer here -> [Is there a way to detect if a browser window is not currently active?](http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active#answer-16043687) – SpYk3HH Dec 02 '13 at 18:47