When a browser tab goes in and out of view, it’s possible you want to do something differently. If you’re writing Apps Script add-ons this is especially true.
 
TabVisibility is a class to allow the detection and testing of visibility across multiple browsers, and to react when their visibility changes.
 
 
 
const tabVisibility = new TabVisibility()
Create an instance

 

Methods

It’s a very simple class, with only these methods
 
methodreturnsdescription
isVisible()Booleanwhether the tab is currently visible
onVisible(action: function) What to do when the tab becomes visible
onHidden(action: function) What to do when the tab becomes hidden

 

Example for Sheets Add-ons

The background of this example is that Apps Script add-on wants to stop polling a spreadsheet for updates when the sheets app is not in view. The mechanics of this are quite unimportant, but TabVisibility is used to provoke a change of polling state in the the Vuex store which is behind the add-on.
 
The entire main app simply looks like this, with a reference to a function to handle tab visibility.

window.onload =  () => {


// initialize everything and register all the components
Store.init().registerAll()

// render vue
new Vue({
el: '#app',
vuetify: new Vuetify(),
store: Store.vxStore
})

// start polling
Store.load()


/**
* there's some action that could be taken when the tab becomes visible
*/
Store.handleVisibility(new TabVisibility())

}
main app with tab visibility handling
And the handler it references

  ns.handleVisibility = (tabVisibility) => {
// if the tab goes out of focus, we want to pause everything
tabVisibility
.onHidden(()=>ns.vxStore.dispatch('pause', true))
.onVisible(()=>ns.vxStore.dispatch('pause', false))
}
Tab visibility handler
 

Summary

Tab visibility is included in How to use Vue.js, Vuex and Vuetify to create Google Apps Script Add-ons and plays an important role in pausing spreadsheet and timers when the add-on is no longer in view.
 
And there’s nothing really more to say, except a reminder that here is the repo for TabVisibility