JavaScript - window focus lost event (trick for older web browsers)
In this article, we would like to show you a simple trick to handle window focus lost event using JavaScript.
This solution is based on the fact, that the setInterval()
method is slowing down on window focus lost.
Note: This is a trick that works both in modern and older web browsers.
In this example, we calculate the time between intervals to check for major changes. When the setInterval()
method slows down, we know that the window focus has been lost.
Run the following example and switch between the tabs for a while to see the result:
xxxxxxxxxx
let focused = true;
let t1 = Date.now();
setInterval(() => {
let t2 = Date.now();
let dt = t2 - t1;
// console.log(dt); // Uncomment this line to see time elapsed between intervals
if (focused) {
if (dt > 1000) {
focused = false;
console.log('Window focus lost!!!');
}
} else {
if (dt < 850) {
focused = true;
}
}
t1 = t2;
}, 800);
Note:
We set the interval to
0.8
s (800
ms), but when you switch the tab it slows down to >1000
ms. However, when you focus back to the current window it "equalizes" the difference (so it can be <800
ms).Uncomment line 6 in the code above to see time elapsed between intervals.
xxxxxxxxxx
const addWindowBlurListner = (callback) => {
let focused = true;
let t1 = Date.now();
let wrapper = () => {
let t2 = Date.now();
let dt = t2 - t1;
if (focused) {
if (dt > 1000) {
focused = false;
callback();
}
} else {
if (dt < 850) {
focused = true;
}
}
t1 = t2;
};
let handle = setInterval(wrapper, 800);
return () => {
if (handle) {
clearInterval(handle);
handle = null;
}
};
};
// Usage example:
const destroy = addWindowBlurListner(() => {
console.log('Window focus lost!!!');
});
// destroy(); // <----- destroys window blur listener