duhaime
duhaime

Reputation: 27594

JavaScript: Listening for browser tab change

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.

Upvotes: 5

Views: 2943

Answers (2)

Han Xiao
Han Xiao

Reputation: 46

use 'visibilitychange' event and 'hidden' attribute.

document.addEventListener('visibilitychange', () => console.log(document.hidden));

Upvotes: 1

duhaime
duhaime

Reputation: 27594

I ended up using:

document.addEventListener('visibilitychange', function() {
  console.log('the tab hath changed');
})

Upvotes: 2

Related Questions