Skip to content

Instantly share code, notes, and snippets.

@burtyish
Last active September 19, 2019 20:55
Show Gist options
  • Save burtyish/0fd0a8b757136acf5efe to your computer and use it in GitHub Desktop.
Save burtyish/0fd0a8b757136acf5efe to your computer and use it in GitHub Desktop.
Page Visibility Service for a Redux/Flux app
/* Based on http://www.html5rocks.com/en/tutorials/pagevisibility/intro/ */
class PageVisibilityService {
constructor(store) {
this.store = store;
this.prop = this.getHiddenProp();
this.register();
}
getHiddenProp(){
var prefixes = ['webkit','moz','ms','o'];
// if 'hidden' is natively supported just return it
if ('hidden' in document) return 'hidden';
// otherwise loop over all the known prefixes until we find one
for (var i = 0; i < prefixes.length; i++){
if ((prefixes[i] + 'Hidden') in document)
return prefixes[i] + 'Hidden';
}
// otherwise it's not supported
return null;
}
isHidden() {
if (!this.prop) return false;
return document[this.prop];
}
register() {
if (this.prop) {
this.evtname = this.prop.replace(/[H|h]idden/,'') + 'visibilitychange';
document.addEventListener(this.evtname, () => this.handleVisChange());
}
}
handleVisChange() {
const state = this.isHidden()
/* This is where your custom code goes, to dispatch an action with the new state */
if (state)
console.log("Page is hidden!")
else
console.log("Page is Visible!")
}
stop() {
if (this.evtname)
document.removeEventListener(this.evtname, () => this.handleVisChange());
}
}
export default PageVisibilityService;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment