In order to append <form> inputs to localStorage, I'm using this piece of code:
function appendToStorage(name, data){
var old = localStorage.getItem(name);
if(old === null) old = '';
localStorage.setItem(name, old + data);
}
userInputs();
function userInputs() {
appendToStorage('oldData', $('textarea[name="textbox"]').val());
}
but I want to retrieve localStorage and process its individual words, split byspaces, every minute or so.
Does this...
function setInput(){
var input = userInputs();
setInterval(function(){localStorage.getItem(name)}, 60000);
}
...make any sense?
Related
I have a folder called https://example.com/foldera and https://example.com/folderb. I want different local storage for these two. I am using simplecart.js. In this the code referring to local storage is
localStorage = window.localStorage,
// storage
save: function () {
simpleCart.trigger('beforeSave');
var items = {};
// save all the items
simpleCart.each(function (item) {
items[item.id()] = simpleCart.extend(item.fields(), item.options());
});
localStorage.setItem(namespace + "_items", JSON.stringify(items));
simpleCart.trigger('afterSave');
},
load: function () {
// empty without the update
sc_items = {};
var items = localStorage.getItem(namespace + "_items");
if (!items) {
return;
}
/************ HTML5 Local Storage Support *************/
(function () {if (!this.localStorage)if (this.globalStorage)try {this.localStorage=this.globalStorage}catch(e) {}else{var a=document.createElement("div");a.style.display="none";document.getElementsByTagName("head")[0].appendChild(a);if (a.addBehavior) {a.addBehavior("#default#userdata");var d=this.localStorage={length:0,setItem:function (b,d) {a.load("localStorage");b=c(b);a.getAttribute(b)||this.length++;a.setAttribute(b,d);a.save("localStorage")},getItem:function (b) {a.load("localStorage");b=c(b);return a.getAttribute(b)},
removeItem:function (b) {a.load("localStorage");b=c(b);a.removeAttribute(b);a.save("localStorage");this.length=0},clear:function () {a.load("localStorage");for (var b=0;attr=a.XMLDocument.documentElement.attributes[b++];)a.removeAttribute(attr.name);a.save("localStorage");this.length=0},key:function (b) {a.load("localStorage");return a.XMLDocument.documentElement.attributes[b]}},c=function (a) {return a.replace(/[^-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u37f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/g,
"-")};a.load("localStorage");d.length=a.XMLDocument.documentElement.attributes.length}}})();
I changed some lines like ,
var url = new URL(window.location.href);
var prefix = url.replace("https://example.com/", "");
simpleCart.each(function (item) {
items[prefix+item.id()] = simpleCart.extend(item.fields(), item.options());
});
...
...
It add prefix for localstorage, but it dosn't prevent from sharing space in localstorage as in foldera it gets foldera prefix and folderb it gets folderb prefix. But the item still present in both folders, only prefix changes.
You can't. There is one local storage per domain.
First answer is you can't as described by others that There is one local storage per domain but there is an alternative solution...
A year ago i was also facing same problem so i create this function you can use this.
but as i am a new developer to JS and can't understand your code so this code may be diffrent from your requirment.
function my_local_storage(name,value,folder){
if(folder=='' || folder==null){
folder = window.location.pathname.slice(1);
}
if(typeof value!=='undefined' && value!==null && typeof(Storage)){
if(value===''){
localStorage.removeItem(folder.name);return true;
}
if(typeof value=='object'){
value=JSON.stringify(value);
}
localStorage.setItem(folder.name,value);
return true;
}
else if (typeof(Storage) && localStorage.getItem(folder.name) !== null)
{
return localStorage.getItem(folder.name);
}
return null;
}
To save new storage for key name and value John just call this function my_local_storage("name","John")
To get value of name key my_local_storage("name")
To remove value of name key my_local_storage("name","")
To Access other folders storage value use my_local_storage("name",null,"folder2")
I need help with pushing 2 data values into localStorage. I know a little about the stringify and parse methods but cant grasp how to implement them.The 2 data values are from "Scores" and "saveName"(a username that is put into an input box).
var Score = (answeredCorrect * 20) + (timeleft);
var saveName = document.querySelector("#saveName");
function Storage() {
localStorage.setItem("User", JSON.stringify(saveName.value));
localStorage.setItem("Scores", JSON.stringify(Score));
var GetStorage = localStorage.getItem("User");
var GetStorage2 = localStorage.getItem("Scores");
return {
first:console.log("GetStorage: "+ GetStorage + GetStorage2),
second:GetStorage,
third:GetStorage2,
};
};
var values = Storage();
var first = values.first;
var second = values.second;
var third = values.third;
As mentioned in the comments you need to parse it once retrieved from storage with JSON.parse, also naming Storage should be avoided.
Since your making a wrapper for localstorage, it could be done like this:
const Store = {
set: (key, value) => localStorage[key] = JSON.stringify(value),
get: key => JSON.parse(localStorage[key])
}
Then you can simply call it like the following, with a set and get methods:
//
Store.set('Score', Score)
Score = Store.get('Score')
//
Store.set('User', saveName.value)
saveName = Store.get('User')
Though you only need to get() on page load as you already have the value in Score/saveName etc.
Im trying to display all the records that are in local storage.
Ive currently only managed to temporarily show records upon creation however they dissapear once refreshing the page.
let tunings = [];
// example {id:1592304983049, title: 'Deadpool', year: 2015}
const addTuning = (ev) => {
ev.preventDefault(); //to stop the form submitting
let tuning = {
name: document.getElementById('name').value,
note1: document.getElementById('note1').value,
note2: document.getElementById('note2').value,
note3: document.getElementById('note3').value,
note4: document.getElementById('note4').value,
note5: document.getElementById('note5').value,
note6: document.getElementById('note6').value
}
tunings.push(tuning);
document.forms[0].reset();
// to clear the form for the next entries
//document.querySelector('form').reset();
//display data
console.warn('added', {
tunings
});
let pre = document.querySelector('#msg pre');
pre.textContent = '\n' + JSON.stringify(tunings, '\t', 2);
//saving to localStorage
localStorage.setItem('MyTuningList', JSON.stringify(tunings));
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn').addEventListener('click', addTuning);
});
This here displays data upon the creation of records however id like to grab every record in local storage and display it on the html page.
//display data
console.warn('added', { tunings });
let pre = document.querySelector('#msg pre');
pre.textContent = '\n' + JSON.stringify(tunings, '\t', 2);
You'll need to parse the data to get it in correct format.
This example relies on having the existence of a storage item called tunings
const data = localStorage.getItem("tunings"); // Store the localstorage data in variable.
// Set it to an empty array incase the storage is empty.
if (!tunings || !tunings.length) {
tunings = [];
} else {
tunings = JSON.parse(data); // Parse the data.
}
console.log(tunings); // Read the data for example.
Microsoft released update kb4088776 in the past couple days, which has had a devastating effect on performance of indexedDb openCursor.
The simple fiddle here shows the problem. With the update, the "retrieval" time is 40 seconds or more. Prior to the update, it is around 1 second.
https://jsfiddle.net/L7q55ad6/23/
Relevant retrieval portion is here:
var _currentVer = 1;
function _openDatabase(fnSuccess) {
var _custDb = window.indexedDB.open("MyDatabase", _currentVer);
_custDb.onsuccess = function (event) {
var db = event.target.result;
fnSuccess(db);
}
_custDb.onerror = function (event) {
_custDb = null;
fnSuccess(null); // should use localData
}
_custDb.onupgradeneeded = function (event) {
var db = event.target.result;
var txn = event.target.transaction;
// Create an objectStore for this database
if (event.oldVersion < _currentVer) {
var customer = db.createObjectStore("customer", { keyPath: "guid" });
var index = customer.createIndex("by_id", "id", { unique: false });
}
};
}
function _retrieveCustomers(fn) {
_openDatabase(function (db) {
if (db == null)
{
alert("not supported");
return;
}
var customers = [];
var transaction = db.transaction("customer", "readonly");
var objectStore = transaction.objectStore("customer");
if (typeof objectStore.getAll === 'function') {
console.log("using getAll");
objectStore.getAll().onsuccess = function (event) {
fn(event.target.result);
};
}
else {
console.log("using openCursor");
objectStore.openCursor().onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
customers.push(cursor.value);
cursor.continue();
}
else {
fn(customers);
}
};
}
});
}
The time to create and add the customers is basically normal, only the retrieval is bad. Edge has never supported the getAll method and it still doesn't after the update.
The only workaround I can think of would be to use localStorage instead, but unfortunately our data set is too large to fit into the 10MB limit. It is actually faster now to retrieve from our servers and convert the text to javascript objects, defeating the main purpose of indexeddb.
I don't have Edge so I can't test this, but does it happen with get too, or just openCursor? If get still performs well, you could store an index (in your example, the list of primary keys; in your real app, maybe something more complicated) in localStorage, and then use that to call get on each one.
Here I have global variable userId, and i want to update it inside signInUserFunction(), to use is in other function. I have tried to define it using var, window, But all these didn't help. This variable doesn't update. As i see its about AJAX async. So, what can i do with it?
And yes, I know that its not good to make authentication with JS, I am quite new to it. So, I am just creating random methods to improve.
var userId = 1;
function signInUser() {
$.getJSON('http://localhost:8887/JAXRSService/webresources/generic/getAllUsers', function(data) {
var items = [];
var i = 0;
$.each(data, function(firstname, value) {
var str = JSON.stringify(value);
data = JSON.parse(str);
var innerId;
for (p in data) {
innerId = data[p].id;
if ($('#nameSignIn').val() == data[p].first_name && $('#passwordSignIn').val() == data[p].password) { //
userId = innerId;
window.location.href = "content.html";
break;
} else {
i++;
if (i == data.length) {
alert("Ощибка в логине или пароле!")
}
}
}
});
});
}
How are you determining whether or not it has been set? It looks like immediately after you set it, you navigate to a different page. When you get to that page, you will have an entirely new window.
Try alerting the value before navigating away.
EDITED: Here is how you could pass it to the other page (but you shouldn't do this in a real app)
window.userId=innerId;
alert(window.userId);
//this isn't a very secure way to do this. I DON'T recommend this
window.location.href = "content.html?id=" + innerId ;
Then in the other page, you could access it off the document.location:
alert(document.location.toString().split("?id=")[1]);
After reading my comments, you may want to try this:
var userId = 1;
function signInUser(){
$.getJSON('http://localhost:8887/JAXRSService/webresources/generic/getAllUsers', function(data){
var items = [], actors = data.Actors, l = 0;
$.each(actors, function(i, o){
l++;
if($('#nameSignIn').val() === o.first_name && $('#passwordSignIn').val() === o.password){
userId = o.id;
// this will redirect before any other code runs -> location = 'content.html';
if(l === actors.length){
alert('End of Loop');
}
}
});
});
}
signInUser();
I would not store sensitive data in JSON such as passwords. Use a database. There is no need to get all the data at the same time either.
Using the idea #mcgraphix proposed (and giving you the same warning...this would certainly not be the way to transfer data like this in a production environment), here is one way to do it:
function signInUser() {
var url = 'http://localhost:8887/JAXRSService/webresources/generic/getAllUsers';
var userId;
$.getJSON(url, function(data) {
$.each(data.Actors, function(index, actor) {
// Cache the values of the #nameSignIn and #passwordSignIn elements
var name = $('#nameSignIn').val();
var password = $('#passwordSignIn').val();
if (actor.first_name === name && actor.password === password) {
// We have found the correct actor.
// Extract its ID and assign it to userId.
userId = actor.id;
window.location.href = "content.html?userId=" + userId;
}
});
// This alert should only be reached if none of the actor objects
// has a name and password that matches your input box values.
alert("Ощибка в логине или пароле!");
});
}
// On the next page...
// Top answer from http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript
// This approach can handle URLs with more than one query parameter,
// which you may potentially add in the future.
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
var userId = getQueryVariable('userId');
Thanks you for help.Ended it all with usage of:
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')