tab-hidden.js 1.08 KB
/**
 * 判断当前tab页是否可见
 *
 * @author: liqi <qi.li@yoho.cn>
 * @date: 2016/11/26
 */

var state;
var isHidden;
var changeEvent;

function tabIsHidden() {
    if (typeof document.hidden !== 'undefined') {
        changeEvent = 'visibilitychange';
        state = 'visibilityState';
    } else if (typeof document.mozHidden !== 'undefined') {
        changeEvent = 'mozvisibilitychange';
        state = 'mozVisibilityState';
    } else if (typeof document.msHidden !== 'undefined') {
        changeEvent = 'msvisibilitychange';
        state = 'msVisibilityState';
    } else if (typeof document.webkitHidden !== 'undefined') {
        changeEvent = 'webkitvisibilitychange';
        state = 'webkitVisibilityState';
    }
    return document[state] === 'hidden';
}


function tabVisible(callback) {
    isHidden = tabIsHidden();
    document.addEventListener(changeEvent, function() {
        if (!isHidden) {
            if (callback) {
                return callback();
            }
        }
    }, false);
}

module.exports = {
    tabVisible: tabVisible,
    tabIsHidden: tabIsHidden
};