log out from browser if the browser closes in asp .net? - javascript

my requirement is bit of complicated .
an user is accessing the data base using the web browser, while accessing the data base if the user is closed the active page instead of log out the session - that session needs to be log out automatically.
can some one guide me how to make this ?
i am used jquery - in the master page.
onbeforeunload - i am getting message leave the page or stay with this page.
even i am getting this messages while login and and view the home page too.

This is the sample code
window.onbeforeunload = function () {
return 'You want to leave?';
};​​
see demo here
I think its possible to send an ajax request and you can saw your server that the user closed the browser's tab.
Also this a jquery plugin called jquery.idle, which is used to identify if the user is active.
Refer this Detecting idle time in JavaScript elegantly will gives you more idea.

You man close the browser or navigate to different page within website? If its closing the browser then the session automatically dies.
Also look into global.asax 's sesson_onEnd event.

Related

Refreshing page via JS snippet

While testing a way in Firefox to reload an HTML page without caching, I've included the following snippet in my code:
<script>
window.setTimeout(function () {
location.reload(false);
}, 5000);
</script>
This reloads the page after 5 seconds, however I get shown the prompt: "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier."
If there a way to do a silent refresh via Javascript, one that doesn't show any prompt? For instance, if I used the refresh Meta tag (HTML), my browser silently refreshes. I want to approximate that same experience, but via JS (and no cache). BTW mine is a Django web app, and I inject the JS code in my Django template.
This is standard behaviour to protect people from submitting form information more than once (eg, prevent double payments in an ecommerce system). Try telling the Javascript to direct to a 'new' page:
Try using this, setting the url to your own;
window.location = "my.url/index.html?nocache=" + (new Date()).getTime();
Answer borrowed from here where there is also an explanation given for why this works -> How can I force window.location to make an HTTP request instead of using the cache?
Have you tried location.reload (true) ? If set to true, it will always reload from server. Set to false it'll look at the cache first.
You are getting this prompt because you ask to reload a POST request. You should always get this prompt when reloading a POST request, as it is not a safe method
However, if you wish, you can explicitely resend a POST request (though you might have difficulties to find back the POST data previously sent). Or explicitely send a GET request to the same URL.

window.location.reload(true) working inconsistently

I've been working on an automatic log-out functionality for my web page. As a part of that, I implemented the window.location.reload(true) in 3 different places in my code. Two of them are automatic, one is attached to a link. The link always works, but the automatic ones don't always work, and I don't understand why.
For the automatic logouts, one set by a debouncer:
var userActionTimeout = debounce(function(e) {
console.log("inaction timeout, reloading page");
window.location.reload(true);
},15000;);
$(document.body).on('mousemove keydown click scroll',userActionTimeout);
Which theoretically should reload the page after a certain amount of inactivity.
The other two uses happen after certain types of AJAX data submission (e.g. blatantly wrong data sent that could only happen if the client was modified) trigger a log out. Of course, any further AJAX submissions are ignored by the server, and the next page the server will serve the client is a login page. In the event this happened inadvertently, AJAX sends the client an error message that includes the following:
refresh to continue session
I also implemented a timeout that also happens if this link is served, which happens after the AJAX response is received:
if (typeof response._forceRefresh !== 'undefined' && response._forceRefresh) {
console.log('reload firing');
/*
some code to insert the link into a spotlight here
*/
setTimeout(function(){console.log('reloading in 3s...');},7000);
setTimeout(function(){
console.log('reloading...');
window.location.reload(true);
},10000);
}
However the issue I'm having is this: Most of the time, the debounce page reload works (tested in firefox & chrome), however occasionally it doesn't. The link always works, but the AJAX response reload is about 50/50. I know it receives the response from the server since the link shows up, but quite often it doesn't actually automatically reload the page.
What is going on?
When ever I get inconsistency on a web page, it usually involves caching that I didn't realize was happening. If you haven't already, look through your project with that in mind and see if there is an effected location that you can force it not to cache a page.
Another idea might be to try using the meta refresh element. There is another thread where this is suggested: auto logout idle timeout using jquery php

Javascript/PHP: Open window to install twitter API then send back user info to main window

I use window.open() to open a popup that will uses OAuth to redirect the user around and install my Twitter application, then closes itself.
Before closing itself however, I would like to send to the main window the username of the client. I tried var win = window.opener; followed by win.someFunction(username); but it is not working, I guess before the "opener" property is lost in the redirections that OAuth does.
Is there any way from the Child Window to find the Parent Window and send data? I checked and there is no window.setName('parent'); and getWindowByName('parent'); hehehe, that would be too good to be true.
UPDATE:
I am using 3-legged authorization
The thing I tried that I'm talking about in the second paragraph comes from this:
is it possible to open a popup with javascript and then detect when the user closes it?
Well turns out I just put a time to detect when the window was closed then sent an AJAX request to get the data I needed.

How to keep user in the same page if the back button has been pressed? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to disable Back button in IE and firefox?
I am developing an one page website(DAM). To enter this site user have to be authenticated. After login if user click on the back button, he is seeing the login page. The login page is not in my control, means it is provided by the oracle content management system, so I cannot add any code there.
What code should I add to my page so that if one pressed the back button he will be navigated to the same page.
I have tried to use onbeforeunload and that worked, but I don't want any confirm message, just wanted to stay on that page.
This is not possible as it is explicitly designed to work that way - if the user hits "back" the browser must return to a previous page. There are a few unreliable techniques out there but ultimately they all fail for one reason or the other.
However... I guess in your case you can do a double-redirect and handle the "bacK" button in your landing page that is immediately after the login?
How single page apps with good usability work
If you want to increase user experience and usability factor of your page, you should be using page hashing/fragments. I'm not going to provide the same (or similar) code that others did, but rather upgrade the experience.
So how about that UX then
Your single-page web application should be changing hash every time when it changes context of its work. That may be defined by user interface or business process that user does in the UI or maybe even individual steps of such processes when it's expected that users would/should be going back to previous process states.
This way your application would function similar to normal web applications that consist of several pages and create a new history entry on the same basis of business processes and their steps (steps in this case are usually full-page postbacks).
So business processes and thinking of your application as a normal multi-page one will give you many useful points when you may change page fragment. Since you can control this you can provide better granularity (usually less) than multi-page web applications.
A simple example where multi-page application history has too many points
Form posts are usually always problematic, so having a history point after postback response is always bad because users hitting F5 resend the same form over and over again (ok browsers do ask you about resending post data but that's still bad experience).
Page fragmenting is the way to go, just use it further than just preventing getting back to logon page.
Completely preventing logon page getting into history stack would be by displaying it on your page within an iframe. You would of course need to detect unauthenticated user and add the iframe yourself and load login in it. After user authenticates you should reload your own page. But you should be aware that detecting login success won't be a straight-forward process.
window.location.replace(URL);
Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.
function win_onkeydown_handler()
{
switch (event.keyCode){
case 116 : // 'F5'
event.returnValue = false;
event.keyCode = 0;
alert("Refresh Not Allowed");
break;
case 08 : // 'BS'
if(event.srcElement.tagName=="INPUT" || event.srcElement.tagName=="DIV")
{
}
else{
event.returnValue = false;
event.keyCode = 0;
//alert("Backspace Not Allowed");
}
break;
case 17 : // ctrl key
event.returnValue = false;
event.keyCode = 0;
alert('Control Key restricted');
}
}
Even i got this in my project but i use to block this on that page using the above script... if u need to block back space u can use that code alone
You are not allowed to control client browser..
Due to some security issues, scripts are not allowed to control client browser..
Try this, it will solve your issue:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="Back" onclick="history.go(0);return true;" />
</body>
</html>
Cheers!!!!

Disallow login to website in multiple browsers/tabs at the same time

I have an ajax heavy website that breaks (or shows incorrect data) when users have it open in multiple browser windows at the same time. So I would like to enforce only allowing the user to be logged in to the website in one tab at a time, whether it is on the same computer or even multiple computers.
I am looking for ideas on how to do this.
Is there any JavaScript method to tell if a certain page is already open in another tab?
Perhaps there is another solution that could involve the server side..
For instance, the client could message the server every say, 1 minute. If the server gets messages from a certain users at a frequency higher than one message per minute, it knows that it is open in more than one window or tab. It can then let one of the clients know that it needs to shout an error to the user.
The idea of messaging the server every one minute does not sit that well with me though.
Any other ideas out there?
EDIT: some people are wondering why I have this problem in the first place. Here it goes:
This is a time tracking application that is fully ajax. You can browse/create/delete/modify timers, projects and clients with ajax, without ever leaving the page. If the website is open in multiple tabs, things will get inconsistent very quickly. Errors usually even occur. For instance, user creates a project and then starts a timer in tab1, tab2 will not show these changes. And since it is all ajax, it will not simply sync when the user clicks some button in the second tab.
Having read the update in your question, what I would really suggest is using WebSocket where available, falling back to Flash socket, long polling and forever iframe for older browsers (actually I'd use Socket.IO to make it all easy - you can use a similar abstraction for whatever environment you are using). That way you can make all of your windows and tabs consistent in real time - problem solved.
That having been said if you don't want to do it for some reason (though what you are trying to do would be a perfect application for WebSockets so think about it) you might use sessionStorage and localStorage to distinguish sessions between tabs or windows for the same logged in user, but it is not widely available yet - see the compatibility table so it would be probably easier to go real-time with a socket.io-like solution where there are a lot of fallbacks available than to restrict visitors to one tab - not to mention the user experience.
There's no way to get information about other tabs/windows in javascript (and for good reason).
The best way I can think to do it would be to print a unique identifier (a timestamp should work reasonably well) in the javascript code for each page, and then it periodically ping the server with that unique ID, and associate it on the server with the user. This way if you have more than one ID belonging to a single user being pinged within a given interval, you can send back a response to the page to warn the user that having multiple tabs open will result in unexpected behavior.
(Like Caspar said above though, you should really figure out why the unexpected behavior is happening and fix that rather than force the user to act a certain way)
This is pretty lo-fi, but I think the simplicity may make it work: you could try having the login open the session in a named window (or change the name of the current window). Then, on load inside the application, check to see if the browser window name is the one you've allowed them to use; if not, pop up an alert, close the window, focus on the named window, if still there. (If not there--i.e., they've already closed the other window--you could let this one stay open, and change the name to the correct name.)
So you're essentially using window.name and window.opener. Rough idea, but an idea.
I have a similar situation and the solution I use is:
on server: at every login you create an unique ID, save it (ex. database) and return it to client.
on client: on every transaction you send this ID to server as a parameter.
on server: if saved and received ID match then allow the request to execute if not refuse it with an error code.
on client: if transaction failed with specific code then you know that "ID" verification failed and you logout user.
So in this way if the same credentials will be used again in any other tab, browser, PC, country,... the old tab will logout user on next transaction request. Or in other words limiting only one opened page per user on the whole world.
Edit:
As I have stopped using html requests for any data communication and use websockets, I register user on server and if same user wants to login from some other location I close the previously used socket (the page automatically logs out).
In this way I also have a way to trigger full page reloads from server in case admin does something that influences users.
Simply use cookies.
$(window).on('beforeunload onbeforeunload', function(){
document.cookie = 'ic_window_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
});
function validateCallCenterTab() {
var win_id_cookie_duration = 10; // in seconds
if (!window.name) {
window.name = Math.random().toString();
}
if (!getCookie('ic_window_id') || window.name === getCookie('ic_window_id')) {
// This means they are using just one tab. Set/clobber the cookie to prolong the tab's validity.
setCookie('ic_window_id', window.name, win_id_cookie_duration);
} else if (getCookie('ic_window_id') !== window.name) {
// this means another browser tab is open, alert them to close the tabs until there is only one remaining
var message = 'You cannot have this website open in multiple tabs. ' +
'Please close them until there is only one remaining. Thanks!';
$('html').html(message);
clearInterval(callCenterInterval);
throw 'Multiple call center tabs error. Program terminating.';
}
}
callCenterInterval = setInterval(validateCallCenterTab, 3000);
}

Categories

Resources