Do something when a session ends - javascript

basically i just need to do something when a session ends in javascript.
I have already tried
window.onbeforeunload = function ()
but is there a way to do it with cookies or something.
i have to do this is javascript because it is to be used for other sites not just mine so i cant do anything server side.

I think you want if all browser tabs of your site are closed?
var state=false;
setInterval(function(){
state=false;
window.postMessage("ami","*");
setTimeout(function(){
try{
if(state==false){
window.lonely();
}
}catch(e){}
},2000);
},5000);
window.addEventListener("message",function(e){
if(e.data=="ami"){
window.postMessage("no!","*");
}else if(e.data=="no!"){
state=true
}});
Use like this:
window.lonely=function(){
alert("im alone :(");
};

Based on your comment "use a session cookie for example when the window is closed and all session cookies are removed", have you considered using window.sessionStorage?
From it's page on MDN:
The sessionStorage property allows you to access a session Storage object for the current origin. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.
(my emphasis added)
From what it sounds like you are trying to do, this may be exactly what you need.
NOTE: Do NOT use this for storing any authentication or other sensitive data.

Related

how to find tab close and clear local storage

I am using onbeforeunload function in javascript but problem is that if browser is refresh then also clear local storage . I want to only clear local storage when browser close not refresh browser
window.onbeforeunload = function(e) {
localStorage.setItem('isLoggedIn', 'false');
};
You can use sessionStorage instead. It is automatically cleared when the browser is closed.
Example:
sessionStorage.setItem("isLoggedIn","true"); // Value will be set to null when browser is closed
You can be needed to learn about local storage, session storage, and Cookies. there are 3 options use for store data but it's one of the different another concept.
local storage store locally and it's permanent if you not remove this or clear browser.
session storage use for containing a status or a token or a user some information.
when you close the browser then session storage remove automatically. (note: if you went any running time you can change it like as logout).
Cookies is another powerful way to store data in the browser or client site. it also allows the time schedule or date. when expiring time or date then it's destroyed automatically.
there are 3 storage are the different their concept and work it's also different storage capacity each other.
Session storage operation:
sessionStorage.SessionName = "SessionData" ,
sessionStorage.getItem("SessionName") and
sessionStorage.setItem("SessionName","SessionData");
Cookie example simple operation:
you can also learn about more:
https://www.quora.com/What-is-the-difference-between-sessionstorage-localstorage-and-Cookies
https://developer.mozilla.org/en-US/docs/Mozilla/Gecko/DOM_Storage_implementation_notes
https://www.w3schools.com/js/js_cookies.asp
=== Thanks ===

How to store cookies instantly and permanently?

I'm developing a website in MVC and I'm setting/updating cookies like this on my action method:
HttpCookie cookie = new HttpCookie("cookie_name");
cookie.Expires = DateTime.Now.AddDays(30);
cookie.Value = cookieValue;
Response.SetCookie(cookie);
Now, this works just fine. But, if I kill Chrome right after this, the next time I access the website, the cookie is not there (or it has an older value and not the last one).
I've checked the 'Cookies' file stored in 'C:\Users\my_user\AppData\Local\Google\Chrome\User Data\Default' and it seems it is only updated approximately once every minute or so. It looks like new cookies are all stored in RAM for a while and then saved as a batch to the hard drive.
I've also tried to set the cookie directly with javascript (using js-cookie library) but the outcome was the same:
Cookies.set('cookie_name', 'cookie_value', { expires: 30 });
Is there a way to store cookies instantly and permanently?

Invalidate a session on browser close in ember-simple-auth?

I'm pretty new to Ember.js and ember-simple-auth, so I hope you can help me.
I'm using ember-simple-auth in my application. What I want to do is to invalidate the session when the browser is closed or the user leaves the page. This is only supposed to happen if the user previosly logged in (thats why put it in the authenticate action).
I tried something like this:
actions: {
authenticate: function() {
var _this = this;
this._super().then(null, function(message) {
_this.set('errorMessage', message);
});
$(window).on('beforeunload',function() {
_this.get("session").invalidate();
});
}
}
The problem is that it does not work when closing the browser. Also when I change the URL (to leave the application, for example www.google.com) it transitions to "/" and does not open the desired URL.
So the question is: How do I invalidate the session when the browser closes (or when the user leaves the application).
Thanks.
I'm not sure how you would handle the case when the user leaves the application (you can probably handle some navigation event and the invalidate the session with this.get("session").invalidate();). To invalidate the session when the user closes the browser though, the best solution is to use the cookie session store and configure a sessionExpirationTime of null so that the cookies are session cookies that get deleted automatically when the browser is closed.

Make cookie presistent even after browser shutdown/restart using Angular.js

I am using Angular for my project, and got into a problem with authentication. On successfull authentication user retrive a token from server, and as long user have this token he can access all the places where he need authentication (i thought its a best way to do this since i use MVC web API as backend, and i dont have sessions). Everything works fine, until i close down my browser, and start it up again $cookieStore and $cookies are empty after restart.
Does anyone have any idea how to make cookie presistent, or are there any smarter way of doing this?
Ive created a test controller with a testview where i have 2 buttons which set and load $cookie before restart it works, if i open a new window while the other one is still up its works too, but as soon i close everything down, coockies is empty.
$scope.Set = function () {
$scope.LoadedData = "test";
$cookies.myFavorite = 'oatmeal';
}
$scope.Load = function () {
var b = $cookies.myFavorite;
console.log("testasdasd" + $cookies);
$scope.LoadedData = $cookies.myFavorite;
}
There are 2 types of cookies: session cookie and persistent cookie.
Session cookie is in memory and only survives until you close the browser.
Persistent cookie will be saved into disc and will be expired based on the Expires property.
The decision to save the cookie as session or persistent is server side, not your client side javascript.
When you use .NET Forms authentication, you can use FormsAuthentication.GetAuthCookie to create a cookie, the second parameter determines if this is a session or a persistent cookie.
I know this question was already answered, but actually you CAN manage cookies persistence client side. Just $cookieStore.
Persistent cookie:
// from your controller
$cookieStore.put('auth_token', token);
// in your module
$http.defaults.headers.common.Authorization = $cookieStore.get('auth_token');
In the module, we are telling angular that we want to use this session everytime any page of our website it's loaded.
EDIT: You may be interested in HTML5 localstorage instead of cookies.

Reliability of ASP Session Timeout warning

I'm looking to warn the user when his or her session times out (I'm having weird timeout problems) and I found the following code:
<%
advanceWarning = 2
jsTimeout = (session.timeout - advanceWarning) * 60000
%>
<script>
window.setTimeout("alert('Session is about to expire');",<%=jsTimeout%>);
</script>
Is this reliable?
Well, it will catch the case where the session times out on the server, assuming no other requests used session in the mean time, and the cookie doesn't expire.
So if you call a web service method or something that uses session, the session time out will be reset and you will have to catch that separately. And if your session cookie expiry (assuming you're doing it that way) is less than your timeout, then session may be lost then too.
In classic ASP, the Session is managed using cookies. You can see more documentation on that here: http://w3schools.com/asp/asp_ref_session.asp. I used to use that site a lot back in the day. If you want more control over the user's session state, you can access the cookies directly (via Request.Cookies and Response.Cookies). http://w3schools.com/asp/asp_ref_response.asp. This may be a better solution in some situations, depending on how much content you are trying to store and how long you want it to persist. If you don't want the session to be refreshed as a 'sliding window', you can always set a timestamp variable in either the session or the cookies collections and gain more control over the timeout that way. One advantage to using the cookies directly is that you can access cookies directly with javascript and can avoid the spaghetti code situation. As I don't know your end goal, I can't say for sure if this will be helpful to you, but the javascript window.setInterval creates a recurring function call and could be used to do asynchronous callbacks to monitor the session state. However, if all you want to do is throw a warning alert(), that is probably overkill and the existing code will work fine.
The above code will not work if there are multiple windows open as you are setting the expiry time from the server and that is valid only for the instant that the request is serviced. This will result in different windows showing the alert at different times. Checking the cookie expiry with some JavaScript periodically is a much better idea.

Categories