可視性を検出するには、次のようなものを試してください。
var state='';
(function() {
var hidden, change, vis = {
hidden: "visibilitychange",
mozHidden: "mozvisibilitychange",
webkitHidden: "webkitvisibilitychange",
msHidden: "msvisibilitychange",
oHidden: "ovisibilitychange" /* not currently supported */
};
for (hidden in vis) {
if (vis.hasOwnProperty(hidden) && hidden in document) {
change = vis[hidden];
break;
}
}
if (change)//this is for detecting without focus, so it works for your second requirement
document.addEventListener(change, onchange);
else if (/*@cc_on!@*/false) // IE 9 and lower
document.onfocusin = document.onfocusout = onchange
else
window.onfocus = window.onblur = onchange;
function onchange (evt) {
var body = document.body;
evt = evt || window.event;
if (evt.type == "focus" || evt.type == "focusin")
{
body.className = "visible";
state='visible';
} else if (evt.type == "blur" || evt.type == "focusout")
{ body.className = "hidden"; state='';}
else {
body.className = this[hidden] ? "hidden" : "visible";}
}
})();
function timeout_trigger() {
if(state=='visible')
{
// window.open('PAGE','_SELF'); OR some ajax
}
}
setTimeout('timeout_trigger()', 30000);
IE 9 以前では onfocusin と onfocusout が必要ですが、それ以外はすべて onfocus と onblur を使用します。