Depending on the answer from SOen you can use Page Visibility API that allows you to detect if a page is hidden.
Browsers that support:
- Chrome 13 +
- Internet Explorer 10 +
- Firefox 10 +
- Opera 12.10+ [ Notes ]
The following code makes use of the API and also tries to provide similar functionality for some browsers with no compatibility.
(function() {
var hidden = "hidden";
// Standards:
if (hidden in document)
document.addEventListener("visibilitychange", onchange);
else if ((hidden = "mozHidden") in document)
document.addEventListener("mozvisibilitychange", onchange);
else if ((hidden = "webkitHidden") in document)
document.addEventListener("webkitvisibilitychange", onchange);
else if ((hidden = "msHidden") in document)
document.addEventListener("msvisibilitychange", onchange);
// IE 9 and lower:
else if ("onfocusin" in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
else
window.onpageshow = window.onpagehide
= window.onfocus = window.onblur = onchange;
function onchange (evt) {
var v = "visible", h = "hidden",
evtMap = {
focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
};
evt = evt || window.event;
if (evt.type in evtMap)
console.log(evtMap[evt.type]);//Troque aqui pelo ajax
else
console.log(this[hidden] ? "hidden" : "visible");//Troque aqui pelo ajax
}
// set the initial state (but only if browser supports the Page Visibility API)
if( document[hidden] !== undefined )
onchange({type: document[hidden] ? "blur" : "focus"});
})();
onfocusin
and onfocusout
are required for IE9 and older , while that all others use onfocus
and onblur
, except for iOS, which uses onpageshow
and onpagehide
.
Where% s are% s change to an Ajax that will notify the server that the user left or entered the page.