Performance of edits to localStorage with JavaScript? - javascript

According to the W3 Web Storage specs, values in localStorage are of type string.
Thus, an entry can't be granularly updated like a subproperty of a JS object and it's only possible to replace the entire key:
Updating/editing localStorage - JSONObject
Assume I want to "secure" user input frequently on the client side in the localStorage, and also update it on model changes on the server (only transmitting changes from server to client). How often can I JSON.stringify() my local data (=ViewModel state) and save it to the localStorage without causing trouble for the user? Is serializing and saving (not transmitting!) e.g. 30KB of data every 5 seconds to the localStorage going to cause lags?
Bonus question: Does any major browser vendor plan on storing JS objects directly in localStorage?

This may not be entirely true; there is a method for updating a single key to an object housed in local storage, and the code is below.
var updateLocalStorageKey = function(obj, key, val) {
var localObj = JSON.parse(localStorage[obj] )
localObj[key] = val;
//reset storage
localStorage[obj] = JSON.stringify(localObj)
}
The working jsbin is here: http://jsbin.com/jesapifa/4/edit?html,js,output
Hope this solves your problem!

Related

How I can get UIWebViews id in java script?

I use UIWebView in the iOS project.
In js code in this webview I use local storage (reading data from local storage by key and writing data to local storage by key).
var items = JSON.parse(localStorage.getItem('key')) || []; //reading
localStorage.setItem('key', newJson); // writing
Now I use only one key for using local storage.
It works fine.
But local storage in common for all UIWebViews in the project (Am I right or not?). And when I use two or more UIWebView in the project (js code is similar for all webviews), that I need use more than one key for using local storage (one key for every UIWebView) in order to every webview use own storage.
How I can define which UIWebView uses local storage now in order to use key for this UIWebView?
How I can get UIWebViews id in java script?
You can save an object in localStorage().
In this way you can save data for more that one UIWebView in client memory and retrieve it easily by key.
An example:
// create an object with some properties (as value use data from UIWebView)
var uIWebViews = { 'uIWebView1': 1, 'uIWebView2': 2, 'uIWebView3': 3 };
// save your object into local storage
localStorage.setItem('uIWebViews', JSON.stringify(uIWebViews));
// retrieve the object from storage, remember to parse it
var retrievedObject = JSON.parse(localStorage.getItem('uIWebViews'));
// get the object
console.log('retrievedObject: ', uIWebViews);
// get a property, equivalent to get a key
console.log('key uIWebView2 has value: ', uIWebViews.uIWebView2);
Live example, please open console to see the result: https://jsfiddle.net/hsf8gf8d/
To let the JS code know what webview it runs in I would call its stringByEvaluatingJavaScriptFromString: method with a predefined JS method that sets a variable in your page. So your JS code could have something like
function setWebViewID(webViewID) {
// save the identifier somewhere and perhaps call other functions
}
Then in the webView, once the page is loaded and all, you call
[myWebView stringByEvaluatingJavaScriptFromString:#"setWebViewID(\"myID\")"]
The trick is usually ensuring that the content is done with any other stuff it does in JS right after loading. If you need something like that I'd recommend using WKWebView, WKUserContentController and to look into addScriptMessageHandler:name:. With that you can properly set up listening for events in JS from the webview.

how to jump between pages with params while not changing the url

recently,i met with a problem that.
there is one page:pageA,there are some in it. the url of which will lead u to another page:pageB .
however ,i want to jump with some params or data while not changing the url of the pageB. is there any good solutions? i'm using react,but not a single page project.
There are couple of ways of doing it like using cookies, spring webflow(if its spring application ) or using Local/Session Storage
Web Storage is a feasible and an easy approach
In page A you can store the value in a local storage using key & value
if (typeof(Storage) !== "undefined") {
localStorage.setItem("anyunique Key Name ", "value which you want to store");
} else {
// Sorry! No Web Storage support..
}
In page B use same LocalStorage's getItem() method to retrieve the value
document.getElementById("someDOM").innerHTML = localStorage.getItem("key");

I am unable to retrieve localStorage data, as stored format appears different?

I am a newbie to programming, and apologies in advance if this has been answered before. I have done some searches and it doesn't look to me like this specific question has been answered.
Before attempting to store a large volume of data in localStorage (HTML5, Chrome, Windows), I have tried some sample data and attempted to store data. When I do a console display before storing the variable shows all the data correctly. I also seem to have some success because I see the sample data in the localStorage via the console.
However, I am baffled that the data appears multiple times in a continuous line. When I try to retrieve the data with a getItem, I get a null. I am not doing anything fancy for either storing or for retrieving data.
The code I use for storing and retrieving are shown below, as also the data in the localStorage as viewed by the Chrome console.
I have also tried JSONstringify in one of my attempts.
Storing:
window.localStorage.setItem('result', zlldata);
Retrieving:
GETzlldata = window.localStorage.getItem(zlldata);
zlldata = JSON.parse(GETzlldata);
Data in the LS look like this: (I tried 2 different approaches, once with 'this.zlldata' and the other time with 'result' in the setItem attempts.
this.zlldata: "undefined"
{"zipLatLong": [
{"zipcode":"35004","lat":"33.606379","longit":"-86.50249"},
{"zipcode":"35005","lat":"33.592585","longit":"-86.95969"},
{"zipcode":"35006","lat":"33.451714","longit":"-87.23957"},
{"zipcode":"35007","lat":"33.232422","longit":"-86.80871"}
]
}
{"zipLatLong": [
{"zipcode":"35004","lat":"33.606379","longit":"-86.50249"},
{"zipcode":"35005","lat":"33.592585","longit":"-86.95969"},
{"zipcode":"35006","lat":"33.451714","longit":"-87.23957"},
{"zipcode":"35007","lat":"33.232422","longit":"-86.80871"}
]
}
Question I have is how do I retrieve the data. I mentioned that data looks different because of all the 'return' characters that show up. Regardless the data should be 'retrievable'. I have allocated enough space in localStorage for the purpose at 5 MB. The format is the same for all records. The purpose of this exercise is a project that I am doing for the course and this approach has other uses. I am aware that in the real world other easier ways are available (e.g. via APIs to websites).
Appreciate any help. Just as additional info, I don;t need to retrieve all data each time, but only need to validate that the zipcode (for eg, exists)
Thanks again in advance and sorry for the lengthy post
To put complex data into localStorage:
localStrorage.setItem("name", JSON.stringify(theData));
To read complex data out of localStorage:
var theData = JSON.parse(localStorage.getItem("name") || "null");
if (theData) {
// It wasn't there, initialize it
}
(Naturally, the above only works with values that can be converted to and from JSON. If you have values that don't convert readily, like dates, you can use a replacer function with JSON.stringify and a reviver function with JSON.parse to handle them.)
Full example on jsFiddle (Stack Snippets don't allow localStorage): https://jsfiddle.net/aj2mq4rz/1
HTML:
<div>
<label>
Name:
<input type="text" id="field-name">
</label>
</div>
<div>
<label>
Age:
<input type="text" id="field-age">
</label>
</div>
<input type="button" id="btn-save" value="Save">
JavaScript:
// On page load, read our data
var theData = JSON.parse(localStorage.getItem("someName") || "null");
if (!theData) {
theData = {
name: "",
age: 0
};
}
var nameField = document.getElementById("field-name");
nameField.value = theData.name;
var ageField = document.getElementById("field-age");
ageField.value = theData.age;
document.getElementById("btn-save").onclick = function() {
// Update our object
theData.name = nameField.value;
theData.age = +ageField.value;
// And save it to local storage
localStorage.setItem("someName", JSON.stringify(theData));
}
You are using:
window.localStorage.setItem('result', zlldata); for storing but using window.localStorage.getItem(zlldata);for retrieving. You cannot retrieve with the value, you need to use the key. So, you need to use getItem('result');
I wrote a tool that will do this for you, that is, allow you to transparently set and get a javascript object (and other primitives) as a localStorage key value. (It does the conversion so you don't have to.) It's called localDataStorage.
To use it, first instantiate your storage object:
localData = localDataStorage( 'my.project' );
Then, store a key value (in this case, your object unchanged):
localData.set( 'key1', '{"zipLatLong": [{"zipcode":"35004","lat":"33.606379","longit":"-86.50249"},{"zipcode":"35005","lat":"33.592585","longit":"-86.95969"},{"zipcode":"35006","lat":"33.451714","longit":"-87.23957"},{"zipcode":"35007","lat":"33.232422","longit":"-86.80871"}]}' );
Then, read it back:
x = localData.get( 'key1' );
--> "{"zipLatLong": [{"zipcode":"35004","lat":"33.606379","longit":"-86.50249"},{"zipcode":"35005","lat":"33.592585","longit":"-86.95969"},{"zipcode":"35006","lat":"33.451714","longit":"-87.23957"},{"zipcode":"35007","lat":"33.232422","longit":"-86.80871"}]}"

how to store javascript html dom document to locastorage

I have document (component tree) 'm' which i am trying to store in the local storage of html5. I tried setting it to local storage. but when i retrieve it back, this m has changed to [object Document].
How do i store document to local storage and retrieve it as document itself?
Below is the code i have tried
the application sends a ajax request to server to retireve events of a calendar and in the request's onsuccess the dom representation of xhtml is recieved.
when the user goes to next week view, the app has to retieve the event from the localstorage. to send the response to the client from the js file, the dom representation is also necessary.so we need to store the dom representation to the localstorage.
my requirements is in 1st picture's console, you can see 'k' is retrieved from the document m and is send as response to the client side.So, what I want is to store this k or m to local storage so i can manipulate it in the same js file.this code is in a separate js file which is used in the xhtml file.
I am using primefaces 4.0, jsf 2.1.
when i use
localStorage.setItem("calendarevents",JSON.stringify(k));
I get an error 'converting circular structure to json'.
You need to store a string representation of the document's html by doing:
localStorage.setItem('calendar', document.documentElement.innerHTML);
When you do this:
localStorage.setItem('calendar', document.documentElement);
...it stores the result of document.documentElement.toString() in localStorage, which doesn't work for your purpose.
localStorage converts every value to a string. To store objects you have to use a workaround.
I guess you could use the method described in this answer
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));

Local HTML 5 database usable in Mac Dashboard wigdets?

I'm trying to use HTML 5's local database feature on a Mac Dashboard widget.
I'm programming in Dashcode the following javascript:
if (window.openDatabase)
{
database = openDatabase("MyDB", "1.0", "Sample DB", 1000);
if (database)
{
...database code here...
}
}
Unfortunately the database-variable remains always null after the call to openDatabase-method. I'm starting to think that local databases are not supported in Widgets...
Any ideas?
/pom
No you will not be able to do the above. And even if you could then you would not be able to distribute the widget without distributing the database assuming it was a MySQL or SGLite. (not sure what you mean by HTML 5's local Db.
here are a number of ways round this:-
You can add a data source which can be a JSON file, or an XML file or and RSS feed. So to do this with JSON for example you would write a page on a server in PHP or something that accessed a database so that when the URL was called the result was a JSON string. Take the JSON string and parse it and use it in the Widget. This will let you get data but not save it.
Another way would be to use the user preferences. This allows you to save and retrieve data in the individual widget.
So
var preferenceKey = "key"; // replace with the key for a preference
var preferenceValue = "value"; // replace with a preference to save
// Preference code
widget.setPreferenceForKey(preferenceValue, preferenceKey);
You can then retrieve it with
var preferenceForKey = "key"; // replace with the key for a preference
// Preference code
preferenceForKey = widget.preferenceForKey(preferenceForKey);
The external call, you could also use REST will let you read any amount of data in and the preferences will let you save data for later reuse that will survive log out's and shut downs.
The Apple site has a lot of information about Widgets and tutorials as well thjat are worth working through.
Hope this helps.

Categories