0

I want to do something when a tab is activated

onvisibilitychange fires when a page is activated and de-activated

I need only the first option, something like:

document.onactivate = function(){ 
  console.log("index.php is visible");
};

Any help?

qadenza
  • 8,611
  • 18
  • 61
  • 108
  • Does this answer your question? [Is there a way to detect if a browser window is not currently active?](https://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active) – Amacado Jul 12 '20 at 10:40

2 Answers2

1

You can check the visibilityState of the document. The event will fire when the page is activated and de-activated, however, this allows you to run code only when the page becomes activated ie: visible.

document.addEventListener("visibilitychange", function() {
  if (document.visibilityState === "visible") {
    // code when page is visible
    console.log("index.php is visible");
  }
});
Nick Parsons
  • 38,409
  • 6
  • 31
  • 57
1

Use condition to check visible

document.addEventListener("visibilitychange", function handleVisibilityChange() {
  if (!document.hidden) {
    console.log("index.php is visible");
  }
}, false);
User863
  • 18,185
  • 2
  • 15
  • 38