According to the response of Soen you can use the Page Visibility API that lets you 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 unsupported browsers.
(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
sane needed for IE9 and older, while everyone else makes use of onfocus
and onblur
, except for iOS, which uses onpageshow
and onpagehide
.
Where are the console.log
s switch to an Ajax that will warn the server that the user has left or entered the page.
You will need a server-side language such as PHP, Python, Ruby (with Rails framework), etc.
– Guilherme Nascimento
I’m using PHP, I would have some example?
– David Damasceno
do you want to count visitors? Or you need relevant data from this visitor (kind for some authentication like login and password)
– Guilherme Nascimento
My doubt is the following, I want to know if the user is on my page, for example if the user goes to another tab account as if he had left, if he goes back to the tab of my site, he will be again on the site.
– David Damasceno
Yes it is possible, but it is not something that is "precise", ie it is not possible to be in real time.
– Guilherme Nascimento
You can help me with a simple example @Guilherme Nascimento
– David Damasceno