Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burtyish/f696a588cc1e08e7f960 to your computer and use it in GitHub Desktop.
Save burtyish/f696a588cc1e08e7f960 to your computer and use it in GitHub Desktop.
Page Visibility Aware HoC (React.js)
import React from 'react';
import exposePageVisibility './page-visibility-aware.js';
const Foo = class extends React.Component {
constructor(props)
{
super(props);
this.state = {
text: ""
};
}
componentWillReceiveProps(nextProps) {
this.setState({
text: this.state.text + "Hidden: " + nextProps.isBrowserTabHidden + "\n"
});
}
render() {
<div>Is this browser page currently hidden?</div>
<textarea name="foo" id="foo" cols="30" rows="10" value={this.state.text}></textarea>
}
}
const PageVisibilityAwareFoo = exposePageVisibility(Foo); // <--- Here's where th HoC is used
export default PageVisibilityAwareFoo;
/* Based on http://www.html5rocks.com/en/tutorials/pagevisibility/intro/ */
import React from 'react';
function exposePageVisibility(Component) {
const PageVisibilityAware = class extends React.Component {
constructor(props)
{
super(props);
this.state = {
isBrowserTabHidden: false
};
this.prop = this.getHiddenProp();
this.register();
}
componentWillUnmount() {
this.stop();
}
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());
}
}
stop() {
if (this.evtname)
document.removeEventListener(this.evtname, () => this.handleVisChange());
}
handleVisChange() {
this.setState({
isBrowserTabHidden: this.isHidden()
});
}
render()
{
return (
<Component {...this.props} {...this.state} />
);
}
};
return PageVisibilityAware
}
export default exposePageVisibility;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment