监听浏览器切屏
为了完成验证用户在切换浏览器tab时进行登录再次认证需求需要监听浏览器切换窗口
if (document.hidden !== undefined) {
document.addEventListener('visibilitychange', () => {
console.log(document.hidden, document.visibilityState)
})
}
- visibilitychange 是h5的一个事件(IE9不支持),可以通过这个事件来暂停css3动画、暂停音乐等;
- document.hidden的值为:true、false;
- document.visibilityState的值为:
- hidden(当浏览器最小化、切换tab、电脑锁屏时)
- visible(用户正在查看当前页面时)
- prerender(文档加载离屏或者不可见
- unloaded(当文档将要被unload时)
function 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;
}
function getVisibilityState()
{
var prefixes = ['webkit', 'moz', 'ms', 'o'];
if ('visibilityState' in document) return 'visibilityState';
for (var i = 0; i < prefixes.length; i++)
{
if ((prefixes[i] + 'VisibilityState') in document)
return prefixes[i] + 'VisibilityState';
}
// otherwise it's not supported
return null;
}
function isHidden()
{
var prop = getHiddenProp();
if (!prop) return false;
return document[prop];
}
// use the property name to generate the prefixed event name
var visProp = getHiddenProp();
if (visProp)
{
var evtname = visProp.replace(/[H|h]idden/, '') + 'visibilitychange';
document.addEventListener(evtname, function ()
{
document.title = document[getVisibilityState()]+"状态";
}, false);