analytics-plugin-tab-events
Version:
Expose tab visibility events plugin for 'analytics' module
88 lines (75 loc) • 2.35 kB
JavaScript
var isServer = typeof window === 'undefined';
var HIDDEN = 'hidden';
/**
* Expose Tab visbility events to analtyics
* Trigger analytics actions when tab is hidden or visible
* @param {Object} [pluginConfig={}] - config
* @return {Object} Analytics plugin
*/
function tabEventsPlugin() {
var pluginConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var events = {
/**
* `tabHidden` - Fires when visitor goes to another browser tab.
*/
tabHidden: 'tabHidden',
/**
* `tabVisible` - Fires when visitor comes back to window from another browser tab.
*/
tabVisible: 'tabVisible'
};
return {
name: 'tab-events',
EVENTS: events,
config: pluginConfig,
bootstrap: function bootstrap(_ref) {
var instance = _ref.instance;
/* Dispatch event when tab visiblity changes */
onTabChange(function (isHidden) {
instance.dispatch({
type: isHidden ? events.tabHidden : events.tabVisible
});
});
}
};
}
/**
* Fire a callback on tab visibility changes
* @param {function} callback - function to run on visibility change
* @return {function} detach onTabChange listener
*/
function onTabChange(callback) {
if (isServer) return false;
var prop = getHiddenProp();
var event = "".concat(prop.replace(/[H|h]idden/, ''), "visibilitychange");
var handler = function handler() {
return callback(Boolean(document[prop]));
};
var attachFunc = function attachFunc() {
return document.addEventListener(event, handler);
};
attachFunc();
return function () {
document.removeEventListener(event, handler);
return attachFunc;
};
}
/**
* Check if tab is hidden
* @return {boolean} true if tab hidden
*/
function isTabHidden() {
if (isServer) return false;
return Boolean(document[getHiddenProp()]);
}
function getHiddenProp() {
var prefixes = ['webkit', 'moz', 'ms', 'o']; // if 'hidden' is natively supported just return it
if (isServer || HIDDEN in document) return HIDDEN; // otherwise loop over all the known prefixes until we find one
return prefixes.reduce(function (acc, curr) {
var prop = curr + 'Hidden';
if (!acc && prop in document) return prop;
return acc;
}, null);
}
export default tabEventsPlugin;
export { HIDDEN, onTabChange, isTabHidden };