How to check using javascript if the user is currently on the page or on another Tab?
I would like to chat add the new message notification, but only if the user is on another Tab.
How to check using javascript if the user is currently on the page or on another Tab?
I would like to chat add the new message notification, but only if the user is on another Tab.
You can use the chat box as the function.
Get its focus or blur event and then add the function for the notification.
If you still want to stick to that, try these: window.onblur
or window.onfocus
events and add the function or not.
Given what you are asking for, which is confirming whether the user is on your page or another tab, I don't think that checking the focus on the chat box is suitable. If a user clicked outside the box at all, then their status would change to inactive.
Mouseover Triggers
Instead, I would detect mouseover events on the <body>
element. Your triggers would look something like this:
<body style="min-height:600px; width:100%;" onmouseover="changeStatus(true);" onmouseout="changeStatus(false);">
Obviously you would have to improve the css or setup a javascript function to make sure that the <body>
element fills the whole screen.
Event Handler
Then you would setup a javascript function that handles the triggers, like this:
<script type="text/javascript">
var i=0;
var pageStatus=true;
function changeStatus(status) {
i+=1;
if (status==true) {
console.log(i+' Page is active');
pageStatus=true;
/* change the users status to active */
} else {
pageStatus=false;
window.setTimeout(function() { if(pageStatus==false) { console.log(i+' Page is inactive'); /* change the users status to inactive */ } }, 1000);
}
}
</script>
I suggest that you have some kind of delay for the onmouseout trigger before it changes the user's status, as sometimes the mouse will go off the page for a second without the user switching to another tab or program. The function I've written above is a little rough round the edges, but should form a sound base to develop the full event handler.
You can set a cookie onload, and delete it onbeforeunload. That way, if the cookie is already set onload, you know the user is already visiting your page.