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 ===
Related
I'm programming a game and I currently have the player speed set to a variable. What I'd like to do is use JavaScript to detect if my computer is playing the game and then change the speed. example: The default player speed is a variable that has a value of 5. If the program detects It's me that's playing the game, change the speed to 10. I would like to do this in JavaScript and I can't figure out a way to achieve this. How would I be able to accomplish this?
Save a value using Cookies or Web Storage and just check if it exists. If it exists, set the player speed to 10.
For example using Web Storage:
Set the value using
localStorage.setItem("check", "1");
and check if it exists using
if (localStorage.check == 1) {console.log("true");}
Some documentations:
Cookies: https://www.w3schools.com/js/js_cookies.asp
Web Storage: https://www.w3schools.com/html/html5_webstorage.asp
JavaScript will not be able to determine your Windows user name. unless it's on the current page or you do AJAX calls to a server-side script to get more information.
But you can do it manually: save in session storage or local storage and then check if something exists, it will save on your computer so it will know:
sessionStorage.setItem('status','loggedIn')
and then:
if (sessionStorage.getItem('status') != null))
//redirect to page
}
else{
//show validation message
}
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?
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.
I would like to enable a user to save their preferences without having to log in. I was thinking of using the user's IP to save their preferences, but this doesn't work for 'workplaces' where multiple people will be on the same IP-connection.
What would be the best way to do this? Basically, I want to store a per-person session without using a database (and hopefully, without having to use a secondary data-store, such as redis).
Is it possible to do this in javascript?
Cookies are your best bet. Tied to the browser of a user, and available for your server too - https://developer.mozilla.org/en-US/docs/Web/API/document/cookie
You may also look at local storage - https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
Understand the difference between the two and make a choice - Local Storage vs Cookies
From your description, I think that saving these preferences on the user's machine is the best option. If it is small amount of data (less than 100KB), then use cookies. If it is big (but still within allowed limits approx 5MB) then use local storage (indexedDB or webStorage).
You can use localstorage. You can store key-value items.
Set value:
window.localstorage.setItem(key, value);
Get value:
var value = window.localstorage.getItem(key);
Example: http://jsfiddle.net/wasnvvo7/1/
Just give the user a unique key to store as a cookie and then use that key to keep track of that user's data. --WARNING!! if the user moves to a different machine or deletes his/her cookies, the session will not be usable.
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.