How to Detect with JavaScript/Jquery If the User Is Currently Active on the Page

How can I detect with JavaScript/jQuery if the user is currently active on the page?

You can watch mouse movement, but that's about the best you're going to get for indication of a user still being there without listening to the click event. But there is no way for javascript to tell if it is the active tab or if the browser is even open. (well, you could get the width and height of the browser and that'd tell you if it was minimized)

How to check if user is currently on the page with JavaScript?

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.

How to tell if browser/tab is active

You would use the focus and blur events of the window:

var interval_id;
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(hard_work, 1000);
});

$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});

To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:

$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");

if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
break;
case "focus":
// do work
break;
}
}

$(this).data("prevType", e.type);
})

Click to view Example Code Showing it working (JSFiddle)

How to check which div page the user is currently viewing using jQuery mobile?

I think you can do it like this :

$(document).on('mobileinit', function(){
$(document).on( "pagecontainershow", function(event, ui) {
console.log($(':mobile-pagecontainer').pagecontainer('getActivePage')[0].id);
});
});

Live Demo


jQuery.mobile.activePage:

jQuery.mobile.activePage is deprecated as of jQuery Mobile 1.4.0 and will be removed in 1.5.0.

Use the getActivePage() method from the pagecontainer widget instead.


As you are using jQM 1.3+ then you can try this code:

$(document).on( "pagechange", function( event, ui ) {
console.log($.mobile.activePage[0].id);
});

Updated demo for jqM 1.3+

How to tell if user just navigated to the page or was waiting on the page?

All users will "come" to the page but if you want to be alerted after they're there for a specific amount of time you could set a timer to send an ajax request after a number of seconds.

For example, the following code would execute the function inform after every 5 seconds. Informing you that the user is still waiting...

setTimeout("inform()",5000);

The function inform would be an AJAX request which informs the backend that the user is waiting. If you only want the request to fire once or after a number of runs stop firing then you could remove it with clearTimeout().

If you want the timeout to only run while the user is waiting on a specific piece of content to load. You could have the clearTimeout() execute when the content you expect will be delayed returns.

You can find some more info on timeouts here.

Is there a way to check if a function is currently running in jQuery?

Set an external flag.

var functionIsRunning = false;

function myFunction() {
if (!functionIsRunning) {
functionIsRunning = true;
//do stuff
functionIsRunning = false;
}
}

The same principle applies to jQuery functions.

Is there a way to detect if a browser window is not currently active?

Since originally writing this answer, a new specification has reached recommendation status thanks to the W3C. The Page Visibility API (on MDN) now allows us to more accurately detect when a page is hidden to the user.

document.addEventListener("visibilitychange", onchange);

Current browser support:

  • Chrome 13+
  • Internet Explorer 10+
  • Firefox 10+
  • Opera 12.10+ [read notes]

The following code falls back to the less reliable blur/focus method in incompatible 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)
document.body.className = evtMap[evt.type];
else
document.body.className = this[hidden] ? "hidden" : "visible";
}

// 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 IE 9 and lower, while all others make use of onfocus and onblur, except for iOS, which uses onpageshow and onpagehide.

Detect if browser tab is active or user has switched away

Now we can use the visibility API.

To deal with the different browser-specific syntaxes, I made this small code :

var vis = (function(){
var stateKey, eventKey, keys = {
hidden: "visibilitychange",
webkitHidden: "webkitvisibilitychange",
mozHidden: "mozvisibilitychange",
msHidden: "msvisibilitychange"
};
for (stateKey in keys) {
if (stateKey in document) {
eventKey = keys[stateKey];
break;
}
}
return function(c) {
if (c) document.addEventListener(eventKey, c);
return !document[stateKey];
}
})();

Usage :

var visible = vis(); // gives current state

vis(aFunction); // registers a handler for visibility changes

Example :

vis(function(){
document.title = vis() ? 'Visible' : 'Not visible';
});

Demonstration page



Related Topics



Leave a reply



Submit