Sometimes, we want to detect if browser tab has focus with JavaScript.
In this article, we’ll look at how to detect if browser tab has focus with JavaScript.
How to detect if browser tab has focus with JavaScript?
To detect if browser tab has focus with JavaScript, we set window.onfocus
and the window.onblur
properties to event listener functions for the focus and blur events.
For instance, we write
let focused = true;
window.onfocus = () => {
focused = true;
};
window.onblur = () => {
focused = false;
};
to set window.onfocus
and window.onblur
to the focus and blur event listener functions.
When the window gets focus, then onfocus
is run.
And when we switch to another window, onblur
is run.
Conclusion
To detect if browser tab has focus with JavaScript, we set window.onfocus
and the window.onblur
properties to event listener functions for the focus and blur events.