I have localstorage for employeeid stored.When i refresh the browser get local storage value like employeeid based on employeeid get some data .when i close the browser i want to clear employeeid in local storage by using angularjs or javascript. I tried the following code.
window.onunload = close;
function close() {
//// do something...
localStorage.clear();
return null;
}
In the above code when i refresh the browser that time also window.onunload fired and clear the local storage values, but i want to clear local storage at the time of browser close only.
If you do not need this to work across different windows/tabs, then you should use sessionStorage instead of localStorage.
Where what you store into localStorage is “permanent”, sessionStorage stores values only until the window/tab is closed, similar to a “session cookie”, that is set without any lifetime – that will live only until the browser is closed (but will be available across different tabs when your site is open in more than one.)
A few more details can be found in these questions:
What is the difference between localStorage, sessionStorage, session and cookies?
HTML5 Local storage vs. Session storage
Maybe that's you're looking for Identifying Between Refresh And Close Browser Actions
Related
I am having a simple problem where I set some test data to local storage after an event listener event.
<script>
document.getElementsByTagName("form")[0].setAttribute("action", "https://www.google.com/");
document.getElementsByTagName('form')[0].addEventListener('submit',
function(){
alert("Test");
localStorage.setItem("persondetails","person");
});
</script>
My problem is:
It adds the dat to session storage on the page that I am currently on but when I navigate to a new page it does not persist.
What am I missing?
What you miss is what SessionStorage is. From mdn:
The sessionStorage property allows you to access a session Storage
object for the current origin. sessionStorage is similar to
localStorage; the only difference is while data stored in localStorage
has no expiration time, 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
with the value of the top-level browsing context, which differs from
how session cookies work.
Consider using localStorage instead. It will persist on new tabs and reloads
I would like to cache some data and I read about Cache Factory, which just caches the data for the current session. But I want to keep my data in cache even after the page was reopened. What is be a better way do that?
You can use LocalStorage, sessionStorage or $cookies service :
https://docs.angularjs.org/api/ngCookies/service/$cookieStore
I think i understand what you're asking here...
If you're trying to keep the data for the current "local session" try using a service/factory, and just store the data in a local variable and create getters and setters for that.
Since the local variable isn't persisted it will be lost when the current local "session" is destroyed (i.e the user refreshes, or closes the window)
Similar to this answer: https://stackoverflow.com/a/14959540/2803660
I'm initializing the token that is generated after I log in to my application in $window.sessioStorage .
var token = this.$window.sessionStorage["apiKey"];
But this token seem to be undefined when I copy the url(after log in ) and open in different browser.I'm redirected back to the login page.
Does $window.sessionStorage holds the values of variables in the same browser window?Or what could be another way to retain the value of token even if I opened the page in different browser window?
That's the right behaviour
The sessionStorage property allows you to access a session Storage
object. sessionStorage is similar to 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.
You can keep information even if the browser is closed and reopend another time by using localStorage, but, as I said, if you open other browser you'll have to set items agains.
Local storage examples here
Code example :
// set something in localStorage
localStorage.setItem('bgcolor', 'green');
// get something from localStorage
localStorage.getItem('bgcolor') // it will output green
With HTML5 and local storage, can JavaScript be used to save the state of a web page?
For example, some sites have increase font size buttons that are most likely controlled with JS. How can the property be saved so that on a refresh the size stays the same? Or is this done without JS?
Your best bet is probably to use localStorage, unless you do not want the settings to persist upon new sessions (you would use sessionStorage in that case). If you have multiple settings, you can store a serialized representation of your settings.
E.g.
var settings = {
fontSize: '11px',
otherConfig: 'test'
};
localStorage.setItem('settings', JSON.stringify(settings));
//then you can retrieve it
settings = JSON.parse(localStorage.getItem('settings'));
console.log(settings.fontSize); //11px
Note that if you want the settings to persist when users connects from multiple computers, you will have to use some server-side support.
Yes, it is done with Javascript. You can use
Cookies
Sessionstorage
This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. 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.
Localstorage
localStorage is the same as sessionStorage with same same-origin rules applied but it is persistent.
The better/easier ones are sessionStorage and localStorage. The problem is that they aren't supported by old browsers.
Instead, dealing with cookies can be a nightmare, but they work on old browsers too.
Yes can save state to localStorage.
assume you have an object :
var settingsObj={
pageClass:'bigFont',
widgetSortOrder : [1,5,3,7]
}
You could save that whole object to one local storage key by stringifying the object. When page loads you would see if that key exists in localStorage and have your javascript do whatever it neds to with those settings
To stringify and store:
localStorage.setItem('mySettings', JSON.stringify(settingsObj) );
To retrieve from storage and convert to js object
var settings=JSON.parse(localStorage.getItem('mySettings'));
I have some pages, on the last page I need to know what choices a user made on the two last pages.
Like this:
a.html
User has three choices here that takes him/her to different urls. I need to somehow save this choice and use it later.
Example:
<script>globalVariable1="firstchoice"</script>
b.html
This is one of three choices page and here the User have 3-4 new choices that takes him/her to different urls. I also need to save this choice somehow for later use.
Example:
<script>globalVariable2="thirdchoice"</script>
c.html
This is the page where I need to know what choices the user has made earlier. To be able to link back to those exact pages if the user wants to go back in my breadcrumb-solution.
Example:
<script>
if(globalVariable1 == "firstchoice"){
//do this
}
if(globalVariable2 == "thirdchoice"){
//do this
}
</script>
Can I do this with some global variables in javascript or how can I solve this?
Thanks
You can use localStorage. A browser API that persists key/value pairs even if you navigate between pages, reload the page or close and reopen the browser.
//setting a value
localStorage["foo"] = "bar";
//getting a value
var x = localStorage["foo"];
Using sessionStorage will also work.
//setting a value
sessionStorage["foo"] = "bar";
//getting a value
var x = sessionStorage["foo"];
Wikipedias Web Storage article describes the difference between localStorage and sessionStorage as:
Data placed in local storage is per domain (it's available to all scripts from the domain that originally stored the data) and persists after the browser is closed. Session storage is per-page-per-window and is limited to the lifetime of the window. Session storage is intended to allow separate instances of the same web application to run in different windows without interfering with each other, a use case that's not well supported by cookies.
You will have to store cookies to track the user's state. Try cookie.js. It has a really simple key-value interface that you can read about on its GitHub page.
Web pages are stateless, so you cannot share global JavaScript variables between pages.
However you can set global variables for your page and containing modules by using the value of the cookie.
Your cookies will be available on all pages of your domain for the current browser.
Example:
//Page 1: Set cookie depending on user choice
$.cookie("choice1", ValueOfChoice1);
//Page 2: Get previous user choice
globalVariable1 = $.choice1("example");
You can read Setting cookies with jQuery if you want more details about how to use cookies.
you can use localStorage or sessionStorage.
Another choice if you're using some server-side language like PHP or Asp.Net is to sore those values in the user's session on the server.