Proper way to detect user's leaving page - javascript

I am building a WebApp (ERP) and I need to display the people currently logged in and active on the page. I managed to get something pretty accurate by listening on the mouse/keyboard events and periodically reporting to the DB.
I don't know how to mark people offline when they close the page. I tried using onbeforeunload, but it obviously fires when the user simply changes pages (click a link inside the ERP, that point to another page in the ERP).
I then tried to use WebSockets, but the problem is the same : everytime the page is realoded, the WebSockets connection is closed.
So I can think of two ways:
Use WebSockets indeed, and replace all links by a call to a javascript function that would somehow tell the server that the user is going to change page (so that the server doesn't mark it as offline). But that doesn't feel right, semantically speaking, links should be links, it simply points to another location.
Use either WebSockets or AJAX and never actually change page: links are replaces by a function that will call for the content, and display it on screen (updating the DOM with Javascript). But again, it doesn't feel right either, because semantically speaking the page would have no meaning and the URL would never change, so the user can't "copy paste" the link of the page to refer to it, right ?
So, is there a proper, clean way of doing this? Thanks for your help.

If each of your pages has a webSocket connection to your server, then on the server you can see when any given page is closed by seeing that the webSocket gets closed.
To avoid thinking that a user has left the site when they are just navigating from one page in your site to another, you simply need to add a delay server-side so that you only report that the user has left your site if there has been no webSocket connection from this user for some time period (probably at least a few seconds).
So, on your server when you detect that the last webSocket connection for this user has been closed, you set a timer for some number of seconds. If the user opens up another page on your site (either via navigation or just opens another page) before the timer goes off, you cancel the timer and count the user as still connected. If the timer goes off, then you now know that the user has been away from your site for whatever time period you picked (say 10 seconds) and to you, this will signify that they have left the site. You can control how long you want that time period to be before you decide that, yes they are gone.
All attempts at trying to "see" the user leaving your page IN the browser with Javascript are going to have holes in them because there are always ways for a web page to get closed without your client-side javascript having a chance to tell your server. The beauty of the webSocket solution is that the browser automatically and reliably tells your server when the page is now gone because it closes the webSocket and your server receives the notification that the socket has been closed.

As I understand you want to compute users active on website/pages.
Identify the user (99% unique id computed):
http://valve.github.io/blog/2013/07/14/anonymous-browser-fingerprinting/ you can use another library, there are few.
On each page send from time to time at page load meaning user is navigating or (60sec you can chose lower time frame meaning user is staing on the page) computed id (fingerprint js) to server (web-socket/ajax)
On server you need to have list of id's with expiration date (60s) increment when new user log's in (stored in database or session).
Retrieve on your website the count (60sec ajax/websocket) of id's having timestamp <= server time - let say 120sec.
Knowing if user is logged, and specify the page:
use an object to be sent at server {fingerprint: 123123124234, logged : true, page: home}
Clear your list if you are not storing in Database the users:
Separate thread (server only) access the object and destroy all nodes older then 10 min or whatever your page session is set.
js timer: http://www.w3schools.com/jsref/met_win_setinterval.asp
Let hope it's helpful, id did something similar using the timer at 5 min to sent to server if user is still on the page, or signal at page load.
Getting the cont of users in frame of 60 sec. And even the users with names present on page :)

Somebody already post this kind of question.
Hope this could help you .
Detect if user has closed ALL windows for a website?

Related

Implementing Presence - When to Change Status to Offline

I am working on implementing a "presence" feature on a website built on a classic asp (vbscript), SQL Server, javascript, IIS7 stack.
The existing authentication/log in system uses sessions, with a default 20 minute session timeout. The user data is stored in a SQL Server table. A cookie is also set when a user logs in, which enables tracking of registered users even when not logged in.
There is a column in the USERS table which holds the state e.g. "online" or "offline". The following is the logic I've come up with thus far:
Status is set to "online" when:
user logs in
a cookie is detected e.g. user returns but doesn't yet log in
Status set to "offline" when:
user logs out
user closes browser (use a javascript event to detect)
user navigates away from the site (not sure yet how best to detect this)
users session expires (handled in global.asa's Session_OnEnd subroutine)
Questions:
Am I overlooking anything in the logic presented above?
What is the best way (within js / classic asp) to detect items 2 and 3 above in the "when to set status to 'offline'" list
Thanks
With 2 and 3 there are js restrictions as to what you can do when js detects a potential leaving of the page. I think all you can do is to show a message before they leave. This means you wont be able to run any js as they are leaving.
Best way to detect when a user leaves a web page?
As Gary said probably the most effective way is to use some ajax to ping a script on the server to update a LastTimeOnline field in your db.
Another way is to use the Session_OnEnd but this may give a false figure as a user could be online for 5 secs which would trigger a 20 minute session.
Best to do the ping really.
All the other logic you have there seems fine.
Just spotted your other comment. Yes if someone leaves their browser open at the page then potentially this could be pinging all day. But then they maybe online so you'd have no choice but to presume that a session is active really. You could always add a bit of js that detects clicks and scrolling to determine activity.
IMHO, the best way to handle 2 and 3 is to have the client send a ping every x seconds, update last access time in DB, then have a logout function on the server side that looks for non-access within x amount of time, and update flag.
These automatic pings will make it seem like there is activity from the client when there may not be, and in this case add some events that capture mouse and keyboard activity. If they stop for some period of time, stop sending pings. Restart pings when activity resumes.
A ping is the only way that you will be 100% sure that the user is still there. Think of example where a user just shuts off the machine. You will not know that they are gone until 20 minute timeout expires. If you set your ping for 60 seconds, you will know very quickly is a user disappears.

How to know how much time a user has our webpage open

I'm trying to guess how much time a user expend on my website in php. To do that, i was thinking that for every new action on my web, i could get the difference between the $_SERVER['REQUEST_TIME'] and the current.
I would also be planning to get stats of my current hosting but i don't know if i can get these values via PHP request.
I would like to get your point of view about using this first and second method, but in advice I should say i'm not really happy with the first option, cause server could be collapsed if the amount of petitions are really high..., otherwise I don't know any other way so if you could help me, it would be wonderful.
On my website i'm using HTML5, CSS3, PHP, JavaScript, JQuery, AJAX and MySQL database.
It is supposed i'd like to store and count all the time users stay logged in my webpage.
Thanks in advice.
There are a few ways of doing this, but only one way to get fairly accurate readings.
PHP Time Difference
This method is what you were talking about with checking the time difference. You would mark the time the user visited the page. Then when the visitor navigates to another page, you subtract the two times and you have the duration the user was looking at the previous page.
To hopefully make myself a little more clear, below is a basic layout of the actions you need to perform to make the PHP time difference method work.
Log the current page URL and time(). Store this as a cookie / session / entry in the database.
When the user visits a page, check the HTTP_REFERER variable and if it matches the page they were previously on, you can calculate the time they were on the last page. The referral check is needed to make sure they are not just opening a new tab and visiting your site again. You will also want to add a time limit so if the value is over 30 minutes it doesn't mark them as visiting the page for over 30 minutes.
Keep repeating those actions and you will have a somewhat okay tracking method. This won't be that specific and in some cases not work if they don't send the referral header.
Javascript Tracking
You can send a "heatbeat" or a "ping" every few minutes to tell your server that the user is still on a specific page. You would want to send the URL the user is currently on as a parameter, don't rely on the HTTP Referral header to be sent. Using this method you can get very accurate readings. You could even track if the user is focused on the web browser window or not to check if the page is being read or just in the background.

An indication of whether the user is still on site

I'm looking for an event that will return when close page whether the user is connected to my site.
onbeforeunload does not help me because it is also activated in efresh, submit, browse from page to page on the same site.
There is no client side event that triggers when a user leaves your site for another site specifically.
If you want to know if users are online you can make repeated ajax calls on a timer, and use a server side session that updates a timestamp of the last request. Using this you can query the timestamps for example, get sessions where the timestamp is in the last 2 minutes.
If polling is an option and you have a server-side backend, you could make a keep-alive script polling the server every x seconds and add it to all pages on your site. If you do not receive enough calls (i suggest at least 3 or so), consider it as a signal the user has logged out. Of course this won't provide an immediate feedback, but should be reliable enough.

Javascript Best Practise: Syncing Browser Windows

I have an html5/javascript application in which multiple users can be viewing the same set of data of any given time. For the sake of a real world example, lets say its a calendar type page.
So user1 is looking has the browser open and looking at the calendar page and user2 is also on the calendar page. User2 makes a change to the calendar and i'd like (as quickly as possible) for those changes the be recognized and refreshed on user1's screen. What is the best way to do this?
I'm thinking about have a mysql table for active users that stores the page they are currently on and a timestamp for its last update, then use ajax calls to ping the server every few seconds and check for an updated timestamp, if its newer than what they have client side, the new data gets sent and the page "reloaded." I am putting reloaded in quotes because the actual browser window will not be refreshed, but a function will be called via javascript that will reload the page. Sort of the way stack overflow performs its update checks, but instead of telling the user the page has changed and providing a button for reload, it should happen automatically. If user1 is working away on the calendar, it seems it might be quite annoying for user2's screen to constantly be refreshing...
Is this a horrible idea? Is pinging the server with an ajax request every few seconds going to cause major slow downs? Is there a better way to do this? I would like the views on either users side to be real time because its important that user1 not be able to update an element on the calendar page that user2 has already changed.
Update: based on some web sockets research it doesnt seem like a proper solution. First its not compatible with older browsers and i support ie8+ and second i dont need real time updstes for all users on the site. The site is an account based applicatiin and an account can have multiple users. The data needs to sync between those users only. Any other recommendations would be great.
You need realtime app for this. You should have a look at socketio. Everytime a user log in, you make him listen for changes on the server. Then when something changed on the server, every users listening are notified.
you can find examples on the official website : http://socket.io/

force to login user on each new browser session?

I want to logout user if browser is closed and force it to login again on turning the browser on.
if (!(isset($_SESSION['admin']))) {
header ('Location: login.php');
}
This doesn't work - because turning off the browser does not mean drop the sessions on server - if I understand well a lot of posts on SO and outside.
Using javascript to delete sessions just before closing the browser often doesn't work because browser will not wait to execute any code if user clicks to close the browser.
Second option is keeping server session alive by sending a js code from client (setInterval - ajax).
Problem here is scenario with multiple pages open on different tabs/windows, i.e. interference between multiple setInterval functions.
I also tried this:
session_set_cookie_params(0);
session_start();
This also doesn't work - after turning off/on the browser index.php is open without redirecting to login.php.
The reason is maybe browser option to automatically restore previously loaded pages.
So, what to do ?
#Axalix wrote:
If session relies on cookies, you just need to keep expiry date empty, then when browser / tab is closed this cookie will be removed from a browser automatically. That's a standard browsers behavior. Yes, the server will still keep it, but since browser doesn't have it, user will need to relogin
You responded:
could that be a possible security issue because cookies are javascript stuff - chengable by client?
Yes cookies can be changed by the client but Axalix' answer from the comments is still the best if you intend to use $_SESSION. If you want to end session on browser exit so that a 2nd user doesn't come later and take over the old session, then you must trust the owner of the session with the session cookie.
If you really want to break access as soon as the client leaves, then $_SESSION is not the best tool to track login state. Instead you could use WebSockets. The socket remains open as long as the webpage is open. Once the socket closes, you can invalidate any login state.
This may be more trouble than it's worth though, so think hard about whether it is really that important. As an alternative, you could use SessionStorage, which is destroyed when the browser closes but it's also available to the user (so a user could just copy and save what's in SessionStorage, then recreate it later).
Basically you need to trust the user who provided you the username and password.
There are couple options but all end up same way. you can either store something in sessionStorage to check session. when browser is closed session storage will be wiped out. or you can add a hidden input field and assign a value per session. if page is newly loaded and value exists that means session is still active, so you can redirect to logout and show login page in either way. but second option may not be usefull if your app has page reloads. I think sessionStorage would be your answer. set session on sessionStorage on login, if it is empty. then check session storage on page load. if it is empty that means user first time on there, since page reload will keep the value.
When Google Chrome is configured to re-open all previous tabs, it won't delete your session cookie. See for example this question asked 5 years ago, but stil an issue (just verified, Google didn't change that behaviour). Unfortunately you can't do much about this behaviour (as far as I know). Without deleting that cookie your session still remains open (unless it is deleted server-side during clean-up).
Best solution to handle an automatic logout is to store a 'last activity time' in your session, update it in every request and in your 'is logged in check' verify that the last activity was not more than, say, 15 minutes ago. If it is more than 15 minutes ago, you could send him to the login.php.
To improve this furthermore (and if this is really an issue for you), you can use a setInterval in javascript to send keep-alive AJAX-calls to the server every 30 seconds or so. In that way you can lower the 'last activity time' (either real activity or automated) limit from 15 minutes to 2 or 1 (leave some room for network hickups).

Categories

Resources