Storing JavasScript settings locally - javascript

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'));

Related

Why can't I use globals in separate html and js files?

I have two html files: index.html and lobby.html. In main.js, which I load in index.html, lobby.html is loaded using window.location.href. I have tried every way of defining globals in main.js (namespaces such as: var Global = {}; Global.variableName = 0; ... Global.variableName = whatever;, simply defining variables out of function scopes: var myGlobal; and even using window. to define and use globals: window.myGlobal = 0; ... window.myGlobal = whatever;). No matter any of these approaches, every time I try to access these "globals" in a separate script in lobby.html, it always throws an undefined error. How does this make any sense?
The answer to your first question, Why can't I ...?, is that you start a new session whenever you load a page. So, any of the Javascript variables from the previous session are gone.
The other (implied) question, How can I keep the value of Javascript variables across sessions? is either to use cookies in Javascript (MDN) or append request variables to the end of your URL then process them when the new page loads: GET (SO)
When a new page is loaded, you are essentially starting a new session as explained by others here and hence the data will be reset. For retaining some data across pages, you could use HTML5 Web storage - Session storage or Local storage as per your business needs.
MDN source
The two mechanisms within Web Storage are as follows:
sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long
as the browser is open, including page reloads and restores).
localStorage does the same thing, but persists even when the browser is closed and reopened.
W3Schools
HTML local storage provides two objects for storing data on the client:
~ window.localStorage - stores data with no expiration date
~ window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

How can I access local browser storage using PDF JavaScript?

I have a PDF file which sets the values of several fields on loading based on a form the user fills out on a webpage. I need to set these fields with different data values each time the PDF is opened. I'd prefer to do this with something like localStorage but I'm not sure how to access localStorage from the PDF JavaScript (or if that's even possible). The fields may be quite long—I'm avoiding sending the data in the URL as a query string (e.g. ...doc.pdf?title=Doc), which may exceed browser URL character limits.
Is there a way to access localStorage or another local browser data storage system using PDF JavaScript? If not, is there a better way I can go about this?
I'm using Acrobat 15 to add JavaScript to my PDF. I will only need to open the resulting PDF in a browser. However, cross-browser solutions are preferred.
If these users are internal to your organization and you can direct them to make some settings changes to their copy of Acrobat or Reader, you can use the Acrobat JavaScript global object to store data that will be persistent across Acrobat sessions. You'll need to disable the global object security policy.
After restarting Acrobat, all documents will have access to the global object. You can set key value pairs using some simple JavaScript...
global.firstName = "Joel"; // Declare firstName to be global
global.setPersistent("firstName", true);
Then later, you can set a field value to the stored global value like this...
this.getField("First Name").value = global.firstName;

How to differentiate browser close and refresh using angularjs?

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

Use javascript to remember what choices the user made on previous pages?

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.

Firefox local storage not available in other tab

I'm creating a firefox extension. I want to use localStorage as a global variable for whole browser. But it is working only for the tab where it was saved. I'm not able to read this value in other tab. How I can make it to be accessible from any tab, or what may be the possible issues ?
I use it like:
localStorage.getItem('variable')
localStorage.setItem('variable','value')
To be more precise, I'm injecting the javascript code into the page when it was loaded. and from injected code i want to save my value to localstorage.
tabs have different url. and my code is trying to use the localstorage when page loaded. but it checking if the localStorage value exists like this:
if(localStorage.getItem('variable')){ ... }
I don't think you can use localStorage as a global variable
localStorage is also the same as globalStorage[location.hostname], with the exception
of being scoped to an HTML5 origin (scheme + hostname + non-standard port) and
localStorage being an instance of Storage as opposed to
globalStorage[location.hostname] being an instance of StorageObsolete which is covered
below. For example, http://example.com is not able to access the same localStorage
object as https://example.com but they can access the same globalStorage item.
localStorage is a standard interface while globalStorage is non-standard so you
shouldn't rely on these.
Please note that setting a property on globalStorage[location.hostname] does not set
it on localStorage and extending Storage.prototype does not affect globalStorage
items, only extending StorageObsolete.prototype does.
Consider using globalStorage and then setting localStorage where need be.
Source: https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Storage#localStorage

Categories