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
  • 9,025
  • 18
  • 73
  • 126
  • 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
  • 45,728
  • 6
  • 46
  • 64
1

Use condition to check visible

document.addEventListener("visibilitychange", function handleVisibilityChange() {
  if (!document.hidden) {
    console.log("index.php is visible");
  }
}, false);
User863
  • 19,346
  • 2
  • 17
  • 41