Skip to content

Instantly share code, notes, and snippets.

@mtcrutch
Created September 10, 2016 15:50
Show Gist options
  • Select an option

  • Save mtcrutch/0bb360a59a5a32a017935b298e57f260 to your computer and use it in GitHub Desktop.

Select an option

Save mtcrutch/0bb360a59a5a32a017935b298e57f260 to your computer and use it in GitHub Desktop.
Wraps a supplied React Component with one that handles watching the page visibility API for changes. When page visibility changes, the wrapper component's internal state is passed down to the supplied component as a prop.
import React, { Component } from 'react';
/**
* Wraps a supplied React Component with one that handles watching the page
* visibility API for changes. When page visibility changes, the wrapper
* component's internal state is passed down to the supplied component as a prop.
*
* @example
* ```js
* const Test = PageVisbility(YourComponent);
* <Test />
* ```
*/
const PageVisibility = Component => (
class PageVisibilityWrapper extends Component {
constructor(props) {
super(props);
this.state = { isPageHidden: false };
this.hidden = null;
this.visibilityChange = null;
this.checkAPI = this.checkAPI.bind(this);
this.handleVisibilityChange = this.handleVisibilityChange.bind(this);
}
// Set the name of the hidden property and the change event for visibility
// https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
checkAPI() {
if (typeof document.hidden !== 'undefined') {
this.hidden = 'hidden';
this.visibilityChange = 'visibilitychange';
} else if (typeof document.mozHidden !== 'undefined') {
this.hidden = 'mozHidden';
this.visibilityChange = 'mozvisibilitychange';
} else if (typeof document.msHidden !== 'undefined') {
this.hidden = 'msHidden';
this.visibilityChange = 'msvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
this.hidden = 'webkitHidden';
this.visibilityChange = 'webkitvisibilitychange';
}
}
componentDidMount() {
this.checkAPI();
if (this.hidden) {
document.addEventListener(this.visibilityChange, this.handleVisibilityChange, false);
}
}
componentWillUnmount() {
if (this.visibilityChange) {
document.removeEventListener(this.visibilityChange, this.handleVisibilityChange, false);
}
}
handleVisibilityChange() {
this.setState({
isPageHidden: document[this.hidden] || false
});
}
render() {
return (
<Component {...this.state} {...this.props} />
);
}
}
);
export default PageVisibility;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment