最新のブラウザの一部は、パフォーマンス向上を目的として、バックグラウンドタブのsetTimeoutとsetIntervalのタイマー間隔が最短で1000msになった。この時間差を利用すると、タブが最前面かどうかを判断することができる。以下、実証コード。
var xGround=function(listeners){
var interval=100;
var preTime=new Date().getTime();
var preStatus=null;
var timer=function(){
var nowTime=new Date().getTime();
var xGround=(Math.abs(nowTime-preTime-interval)<100)?"fg":"bg";
var switchFlag=((preStatus||xGround)!==xGround);
switch(true){
case (xGround==="fg")&&switchFlag:
listeners.switchForeGround&&listeners.switchForeGround();
case (xGround==="fg"):
listeners.foreGround&&listeners.foreGround();
break;
case (xGround==="bg")&&switchFlag:
listeners.switchBackGround&&listeners.switchBackGround();
case (xGround==="bg"):
listeners.backGround&&listeners.backGround();
break;
}
preTime=nowTime;
preStatus=xGround;
};
setInterval(timer,interval);
};
var obj={
switchForeGround:function(){console.log("switch foreground");},
switchBackGround:function(){console.log("switch background");},
foreGround:function(){console.log("foreground");},
backGround:function(){console.log("background");}
};
xGround(obj);
var interval=100;
var preTime=new Date().getTime();
var preStatus=null;
var timer=function(){
var nowTime=new Date().getTime();
var xGround=(Math.abs(nowTime-preTime-interval)<100)?"fg":"bg";
var switchFlag=((preStatus||xGround)!==xGround);
switch(true){
case (xGround==="fg")&&switchFlag:
listeners.switchForeGround&&listeners.switchForeGround();
case (xGround==="fg"):
listeners.foreGround&&listeners.foreGround();
break;
case (xGround==="bg")&&switchFlag:
listeners.switchBackGround&&listeners.switchBackGround();
case (xGround==="bg"):
listeners.backGround&&listeners.backGround();
break;
}
preTime=nowTime;
preStatus=xGround;
};
setInterval(timer,interval);
};
var obj={
switchForeGround:function(){console.log("switch foreground");},
switchBackGround:function(){console.log("switch background");},
foreGround:function(){console.log("foreground");},
backGround:function(){console.log("background");}
};
xGround(obj);
解説は省略。
コメント (2)
ちなみに、まさにそういう仕様も用意されています。 http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html
今のところ、Chrome開発版、IE10 Preview版で実装されています。
投稿者: Os0x | 2011年07月06日 10:04
日時: 2011年07月06日 10:04
情報ありがとうございます。
ホント、そのままのものですね。
投稿者: Kanasansoft | 2011年07月14日 23:39
日時: 2011年07月14日 23:39