Sometimes, we want to detect if user changes tab with JavaScript.
In this article, we’ll look at how to detect if user changes tab with JavaScript.
How to detect if user changes tab with JavaScript?
To detect if user changes tab with JavaScript, we listen to a few events.
For instance, we write
window.onfocus = (ev) => {
console.log("gained focus");
};
window.onblur = (ev) => {
console.log("lost focus");
};
to set window.onfocus
to a function that’s called when the tab is in focus.
And we set window.onblur
to a function that’s called when the tab loses focus.
Conclusion
To detect if user changes tab with JavaScript, we listen to a few events.