Skip to content

Commit

Permalink
fix: unsafe read from document in server-side rendering
Browse files Browse the repository at this point in the history
Currently, this module fails in SSR because it reads from the `document` global variable when it is evaluated at compile time. This fix moves reading the `document` variable from the top level of the module, into the body of the `activityDetector` function, whose contents are not evaluated when bundling. This allows the module to work as-is in apps that do SSR.

See this issue: tuenti#10
  • Loading branch information
louh authored Dec 22, 2020
1 parent 866d1e2 commit 52bcc63
Showing 1 changed file with 15 additions and 16 deletions.
31 changes: 15 additions & 16 deletions src/activity-detector.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,6 @@ const DEFAULT_INACTIVITY_EVENTS = ['blur', 'visibilitychange'];

const DEFAULT_IGNORED_EVENTS_WHEN_IDLE = ['mousemove'];

let hidden, visibilityChangeEvent;
if (typeof document.hidden !== 'undefined') {
hidden = 'hidden';
visibilityChangeEvent = 'visibilitychange';
} else {
const prefixes = ['webkit', 'moz', 'ms'];
for (let i = 0; i < prefixes.length; i++) {
const prefix = prefixes[i];
if (typeof document[`${prefix}Hidden`] !== 'undefined') {
hidden = `${prefix}Hidden`;
visibilityChangeEvent = `${prefix}visibilitychange`;
break;
}
}
}

/**
* Creates an activity detector instance
*
Expand All @@ -55,6 +39,21 @@ const activityDetector = ({
initialState = DEFAULT_INITIAL_STATE,
autoInit = true,
} = {}) => {
let hidden, visibilityChangeEvent;
if (typeof document.hidden !== 'undefined') {
hidden = 'hidden';
visibilityChangeEvent = 'visibilitychange';
} else {
const prefixes = ['webkit', 'moz', 'ms'];
for (let i = 0; i < prefixes.length; i++) {
const prefix = prefixes[i];
if (typeof document[`${prefix}Hidden`] !== 'undefined') {
hidden = `${prefix}Hidden`;
visibilityChangeEvent = `${prefix}visibilitychange`;
break;
}
}
}

const listeners = {[ACTIVE]: [], [IDLE]: []};
let state;
Expand Down

0 comments on commit 52bcc63

Please sign in to comment.