Prevent user from holding f5 for more than x seconds? - javascript

Is there a way to bind a jQuery event to pop off after a visitor holds a button for more than, say, 3 seconds? In this case I'd like to do something after a user holds f5 for 3 seconds.
I've found a solution that prevents the refresh when user presses f5 here:
Disable F5 and browser refresh using javascript
However, this isn't quite what I'm looking for as I'd like to allow my users to refresh pages but prevent them from placing a rock on the f5 button so to speak (it's an online game where you can do tasks by refreshing the page).
Is what I'm trying to do even possible?
EDIT: I am looking for a short-term, quick, client-side fix. The server side of things will be solved later on.

This is the kind of problem you really need to solve server side. If the task can be accomplished by refreshing the page, then it can be accomplished by a bot or a line-or-two of script that disables your check. Doing this client side won't really help you.
All you need to do in that case is on the users session, track the last time that action X was performed, and don't perform it again unless more than Y seconds have passed, and tell the user off for trying to do it too fast.
Edit: As a quick hack, what you could possibly do is configure your webserver to supply a cache-control header in the response for affected scripts with a value set to have the content expire in Y seconds. This may (emphasis on may, test this properly first!) prevent the client from re-requesting the page on a normal 'F5', however a force refresh (ctrl+f5 in some browsers) won't be affected by this.
Although again if the issue is that users are exploiting this issue, fixing it client side won't work for very long and users will quickly discover another way around.

PhonicUK's answer (do it server side) is the only correct way to handle this. But you said in a comment on that answer:
I was just asked to apply a quick client-side fix for now. That's why I'm asking if it's possible.
It's possible to do something that will get bypassed, like this (here I'm assuming you use a jQuery cookie plugin):
(function($) {
$(document).on("keydown", function(e) {
var lastRefresh, now;
if (e.which == 116) {
now = new Date().getTime();
lastRefresh = $.cookie("lastRefresh");
if (lastRefresh && (now - parseInt(lastRefresh, 10)) < 3000) {
e.preventDefault();
}
$.cookie("lastRefresh", now);
}
});
})(jQuery);
Again, though, the users will find a way around it.
Be sure to run the script through the Closure compiler or a really good obfuscator. :-)

Related

Killing session when browser is closing

I need to kill the session when the user closes the browser or redirects into some other page.
I can see the following options of achieving this functionality:
Use no session login. It's not my case, because I'd have to change a lot and I also use sessions for some other data.
I could use something like this:
window.onunload = window.onbeforeunload = (function () {
...
})
And from this code call the action that cleans the session and performs logoff.
Sounds nasty but what is also important - this JavaScript code works only in IE.
I could create some nasty code that uses some dummy calls, let's say every minute, just to say the server that the user is still alive.
But it's really nasty. It would use useless load on the server, lots of useless calls and in the case if some call was lost(because of the connection issue or something) the user would logg off.
Any other options?
You've left off #4: Don't do anything, have sessions time out after a reasonable period (say, 20 minutes); if they try to do something on that page after being gone for 20 minutes, just show a page telling them their session has expired and to log in again. That's usually the simplest option.
If you don't want to do that, #3 is really your only viable option, but once/minute is probably overkill. Set the session timeout to 20 minutes, remember when the user has done something, and if they're idle for (say) 15 minutes do a proactive call on their behalf. But even then, I'd limit how much I'd do this, after a couple of hours you might want to just redirect them to the login page.
I think this answer is the right way to go:
In javascript, how can I uniquely identify one browser window from another which are under the same cookiedbased sessionId
Set a unique window id:
window.windowIdClient = "{978d-478ahjff-3849-dfkd-38395434}"; //or another randomly generated id.
Store that windowId in the database, along with the ip-address and the session-id. If those three do not match than the user is logged out.
In addition, if didn't think of T.J. Crowder's option, I use it myself.

Poor Performance in Loading content using AJAX

I need your help badly in determining the cause of this problem. This is a hotel management system that keeps track of checked in guests and monitors them if their time is up. I'm using setTimeout as suggested by Mr. A. Wolff (Slow website after some time (with ajax interval of 10 seconds)) in this discussion. It's reloading the content every 5 seconds now but as you can see, the debugger is consuming 10 seconds in getting 56KB of data.
The problem still exists. I have done my researches about modals and timeouts and I am close to giving up. I just need a clue on where to start.
The computer is where the files are located. Technically, it's a server and at the same time, being used as a client for the system.
Here's a screenshot for the debugger. Thank you.
UPDATE:
I removed the setTimeout from the function itself so basically, nothing's reloading the page. Then I opened a checkin page, things got faster, and I mean so fast now. So I think this is what I need to do, I need to stop the function from reloading the page IF I OPEN A MODAL. The reason is that, if the modal closes, it's going to reload the PAGE anyway. So it must be a good idea to stop the recurring function when a modal is opened. Any suggestions?
UPDATE 2:
Here's the link of the script being executed:
https://www.dropbox.com/s/azi51w0pzp69kgh/checkin.php
Here's the live site: http://greenenergiesllc.com/temp
Login: removed by moderator
Password : removed by moderator
i suggest you don't use settimeout,use setinterval for 5 sec instead of it.
if you pull large data from server you must use json.
and also don't create js timer in same time,the server couldn't response over ajax requests.

Triggering a DB call on browser leaving current page?

I've got an application that I intend to set a lock flag in my database that would exclude others from viewing that same page if set.
However, once set - I have no idea how to "unset" it. I could make it up to the user to unset the flag, but that seems unnecessary.
I'd want to simply look for the browser to leave the page, make a call to the database, and unlock the page.
How does one do this "type" (not looking for the exact way) of thing with JSF/Javascript/jQuery (all options)
There's really not a reliable way to do this, that I've seen anyway.
You can use the browser's onbeforeunload event to tell the server, "Hey I'm leaving the page now.". The issue is you can't actually block the page from unloading. If the user is actually closing the browser, any open sockets are going to be closed immediately. Your web server may or may not get the request in time. I've had very flaky results with this approach.
One approach that might work is to employ some sort of timeout mechanism. The page would ping the server every 30 seconds or what not, saying "I'm still here." If the server did not get this update after a few minutes, it would invalidate the session and free up that document. Perhaps this could be optimized by checking for the last ping when someone new came along. One issue with this is if someone left the page, the next user might have to wait a minute or two before they could go to the page. You'd then have to find a ping frequency that doesn't flood your server with traffic, but also doesn't make the next user have to wait too long.
It's also possible to combine these two methods. When the user leaves the page, trap the onbeforeunload event and immediately invalidate the session. However, if it didn't work, the session would time out after a minute of not being pinged.
Are there better solutions?
If you really need to lock a document in a web app so multiple users can't edit it, you might want to investigate your overall design. Are you afraid of users clobbering data? If so, maybe employ a mechanism that can resolve merge conflicts, or detect if both sets of changes can be combined.
If you wanted to go truly Web 2.0, you could design something similar to Google Docs, where changes appear live as they're made. No need for a Save button anywhere!
Sending a "keep-alive signal" might be an option. Something along these lines on the frontend side, combined with session cookies.
setInterval(function() {
var img = new Image();
var src = "http://examle.com/keepalive.gif?cachebuster=" +
Math.ceil(Math.random() * 10000 );
}, 1000);

I want to detect when user close browser window?

I have Example and i need to kill the session when user close his browser window.
i tried page_unload() not working.
the example is:i have parent windows and window will open from it i need to delete session when user close the child window.
please i need some help.
This is not something that's provided for in the normal web http protocol. There's no real way to know for sure when the browser closes; you can only "sort of" know. You have to throw together an ugly hack to get any level of certainty and even then it's bound to fail in plenty of edge cases or cause nasty side effects.
The normal work-around is to send ajax requests at intervals from the browser to your server to set up a sort of "heartbeat". When the heartbeat stops, the browser closed and so you kill the session. But again: this is a horrible hack. In this case, the main problems are that it's easy to get false positives for a failed heartbeat if the server and client to get out of sync or there's a javascript error, and there's a side effect that your session will never expire on it's own.
You can do this with an window.onbeforeunload handler that posts back to a sign out page.
function CloseSession( )
{
location.href = 'SignOut.aspx';
}
window.onbeforeunload = CloseSession;
This is the duplication question.. chk out here
Closing the browser should actually clear the session variables an ASP.net session id
https://stackoverflow.com/questions/920042/kill-server-side-session-on-browser-window-close-closed
Unfortunately this is not possible. You can find examples on the web claiming that they can do that, but they are flawed sometimes in a very subtle way.
There is no consistent way to detect the browser closing through javascript. If you are concerned about having too many sessions hanging, reduce the session timeout on your server. If you do that you will also want to notify your users that they need to remain active in order not to lose any work.
If your client-side script sent an AJAX heartbeat to your server-side app, you might use a missing beat to close the session.
You have reference of all child windows in parent window
you need onfocus to check for child windows
so when your parent get focus check if child is there or not

How to detect browser closing?

In my web app, when a user logs in, I add his Id to a vector of valid Ids in the servlet, when he logs out, I remove his Id from the vector, so I can see how many current users are active, if a user forgets to log out, my servelt generated html has :
<meta http-equiv="Refresh" content="30; url=My_Servlet?User_Action=logout&User_Id=1111">
in the tag to automatically log him out.
But I've noticed many users are there for ever, never logged out. I found out why, by closing their browsers, they never manually or automatically logged out, so their user Ids will never be removed from the valid user Ids vector.
So, my question is : how do I detect users closing their browsers, so my servlet can remove their Ids from the vector ?
I see some light at the end of the tunnel, but there is still a problem, my program has something like this :
Active User List :
User_1 : Machine_1 [ IP_1 address ]
User_2 : Machine_2 [ IP_2 address ]
User_3 : Machine_3 [ IP_3 address ]
...
How do I know, from the session listener, which user's session has ended and therefore remove him from my list?
I was hoping when the session ends, the HttpServlet's destroy() method would be called and I can remove the user Id in there, but it never gets called when user closes his browser, why? And is there any other method in the HttpServlet that gets called when a session closes?
There is no way to know on the server-side (unless you are using some JavaScript to send a message to the server) that the browser has closed. How could there be? Think of how HTTP works - everything is request and response.
However, the application server will track when Sessions are active and will even tell you when a Session has been destroyed (such as due to time-out). Take a look at this page to see how to configure a HttpSessionListener to receive these events. Then you can simply keep track of the number of active sessions.
The number of active sessions will lag behind the actual number of current users, since some period of (configurable) time has to elapse before a session is timed out; however, this should be somewhat close (you can lower the session-timeout to increase the accuracy) and it is a lot cleaner and easier than 1) tracking Sessions yourself or 2) sending some asynchronous JavaScript to the server when a browser is closed (which is not guaranteed to be sent).
I suggest you remove the ID when the Servlet engine destroys the session. Register a HttpSessionListener that removes the user's ID when sessionDestroyed() is called.
Diodeus's idea will only help you detect that the session is over more immediately.
in JavaScript you can use the onbeforeclose event to pass a call back to the server when the user closes the browser.
I typically use a synchronous Ajax call to do this.
I had to do that recently, and after some searches, I found some solutions on the Net... all of them non working universally!
onbeforeclose and onclose events are used for this task. But there are two catches: they are fired when the user reload the page or even just change the current page. There are tricks to see if the event is actually a window/page/tab closing (looking at some Dom properties going haywire on closing event), but:
They are browser dependent
The tricks are undocumented, thus brittle
And actually they vary along the browser version/update...
And worst of all, these events are now ignored by most modern browsers, because they have been abused by rogue ads popping out windows when browser was closing. They are not fired in Safari, Opera, IE7, etc.
As pointed out, most Web applications with login destroy the user session after a while, eg. half an hour. I was asked to logout on browser closing to free faster a precious resource: licenses. Because users often forget to log out...
The solution I gave was to ping with an Ajax request (sending the user ID) the server on regular intervals (say 1 minute). If the server receives no ping for, say, 3 minutes, it disconnect the user.
There is no foolproof way to do what you're trying to do, but both sblundy and Diodeus have plans that will cover most circumstances. There is nothing you can do about someone who turns off Javascript in their browser, or their internet connection goes down, or their power goes out. You should just cull sessions after a certain period of inactivity (which I think is what sblundy's suggestion of listening for session destruction will do).

Categories

Resources