5

I'm trying to trigger an event on browser tab change in JavaScript. MDN advertises a browser.tabs.onActivated() function, and shows full support in Chrome, but my Chrome console barks when I try to access either browser or tabs global variables.

Does anyone know how to trigger an event on change of browser tab? I'm looking for a vanilla solution without external library dependencies.

duhaime
  • 25,611
  • 17
  • 169
  • 224

2 Answers2

2

I ended up using:

document.addEventListener('visibilitychange', function() {
  console.log('the tab hath changed');
})
duhaime
  • 25,611
  • 17
  • 169
  • 224
1

use 'visibilitychange' event and 'hidden' attribute.

document.addEventListener('visibilitychange', () => console.log(document.hidden));
Han Xiao
  • 46
  • 2