html5 localstorage not working the way I want - javascript

I am using HTML5's localstorage to save two variables and load them when the user refreshes the page but something doesn't work properly when loading the saved item:
var's:
var cookies = 0;
var cursors = 0;
saving code:
window.setInterval(function(){
var save = [cookies, cursors];
localStorage["save"] = JSON.stringify(save);
console.log("Saved game");
}, 1000);
loading code:
function load() {
var state = JSON.parse(localStorage["save"]);
console.log("Loaded game");
}
What my console show's on page load:
[13,1]
Loaded game
[0,0]
Saved game
[0,0]
Saved game
[0,0]
Saved game
Etc.
The load() function gets called on body load (<body onload="load()">
and I DO get the console message "Loaded game"...

You syntax seems fine. However, JSLint recommends using dot notation on localStorage:
localStorage.save = JSON.stringify(save);
and
var state = JSON.parse(localStorage.save);
Then you can just add your state variable to the console.log statement to check it:
console.log("Loaded game: "+state);
Remember, your values have been saved as an array, so you'll have to access them with state[0] and state[1] to get the individual values.

There is nothing wrong with your localStorage access. Also, you don't need to try sessionStorage if is localStorage what you are looking for.
The problem, I think, is with how are you dealing with your data.
Judging by your code, you are reading the localStorage data and storing it into a local variable called state and doing nothing more with it.
Fact: if you are REALLY getting to save your data to localStorage with the
localStorage["save"] = JSON.stringify(save);
then the
var state = JSON.parse(localStorage["save"]);
would actually work, if performed anytime after the previous snippet. So, if your application is actually getting to run the snippet where you save the data, then later when you run the load function, the local variable state will have the content [0, 0].

Related

Retrieving data objects from localstorage and reload them into array

I have taken some key points from this site already when it comes to transferring data to and from local storage. However, it does not seem to work properly. In short, I am trying to load data in the form of an array containing objects, to and from the local storage. I am aware that it is saved as a string within local storage and have then used JSON formatting to solve that problem, it is also where I think the problem might be when there is objects within objects. However, in its current state, it does not seem to work. Any ideas?
var students = [{name: "Petrina", age: "20"}];
function saveList(){
localStorage.setItem('somekey', JSON.stringify(students));
console.log("Saved to Local");
}
function loadList(){
students = JSON.parse(localStorage.getItem('somekey'));
}
The code gives no errors, I am using the functions in relation to loading the window.
window.onload = () => { loadList() }
You've added that you are calling from onload, and,
in your code you are loading into students.
add to the beginning of your code:
var students;.
Note: Some Objects need special handling.
For example: Date:
var date = new Date();
localStorage.date = JSON.stringify(date);
date = new Date(JSON.parse(localStorage.date));
Answer before additional information:
key is a method of localStorage.
Don't use it.
Use students instead, for example.
Storage.key()
(This is assuming that you call the functions)
var students = [{name: "Petrina", age: "20"}];
function saveToLocalStorage(key, value){
localStorage.setItem(key, JSON.stringify(value));
console.log("Saved to LocalStorage");
}
function loadFromLocalStorage(key){
console.log("Loaded from LocalStorage");
return JSON.parse(localStorage.getItem(key));
}
console.log("students: "+students);
saveToLocalStorage("stu", students);
var st2=loadFromLocalStorage("stu");
console.log("st2: "+st2);
cannot be run in a snippet: sandboxed, no access to localStorage - cross origin.
It got solved! - I am unsure what the problem was. I cleared all the calls for all functions and debugged the save and load function 1 at a time whilst watching the local storage data. The problem to begin with was that it simply did not save the data that got updated during runtime, hence it just kept loading values that always were the same. #iAmOren's idea by creating a function that returns a value might have done it, however I am unsure why. Thanks for the responses & Support!
Are you missing a call to your saveList function?
Calling saveList before calling loadList works as you expect.
Please refer: https://codesandbox.io/s/strange-brown-3mmeq?file=/index.html

I was wondering if someone could teach me how to use cookies in my code

I'm trying to make a "Window.alert game" in a browser window for fun, but I can't figure out how to use cookies to save player data if they mess up or close the window. Can someone help me?
LocalStorage is indeed your best option for saving data semi-permanently. One thing to remember is that localStorage only supports strings, so if you need to store more complex objects, you should JSON.stringify them (and JSON.parse the result when loading data).
A simple pattern is to use a single object to store your state, and to save this state to localStorage whenever a change is made to it (so that your latest data is always persisted). You can also listen to the window.beforeUnload method to save your state right before the window closes, but this may not always work (eg: if your browser or tab closes unexpectedly).
Here is an example of what you can do:
// saves your state to localStorage
function save(state) {
localStorage.setItem('state', JSON.stringify(state));
}
// execute code when the document is loaded
document.addEventListener('DOMContentLoaded', function () {
// load your state from localStorage if it has been previously saved
// otherwise, set the state to an empty object
var state = JSON.parse(localStorage.getItem('state')) || {};
// show your name if previously saved
// otherwise, prompt for a name and save it
if (state.name) {
alert('Your name is: ' + state.name);
} else {
state.name = prompt('What is your name?');
save(state);
}
});
To clear localStorage, you can call localStorage.clear().

Keep array data on page load

I am trying to keep values in my array on different pages (Wordpress), I'm trying do this via global array but it doesn't seem to work. On "page-1" I am filling the array with data, the same script is loading when I click "page-2". I would be grateful if you point how to fix my problem.
var myArray = new Array();
// Here is issue my myArray with data becomes empty after second load
myArray = {
tablica: []
};
jQuery(document).ready(function(){
// need my array over here
});
It will again reinitialize on next page. You can use local storage for get value from first page to another page.
Unless your app is a spa, a new html page is loaded on navigation. Therefore your JS is re initialise. Global variable does not persist on navigation.
Use local storage, session storage or a server side solution.

Html Storage resets every refresh, initialize function not working

For a website I am working on, I am trying to keep information on how many items you buy to be shown across html pages. Researching how to do this has led me to believe that Html sessionStorage is the best way to do this (if there is a better/easier way please let me know). Yet, whenever I refresh the html page or go to another page the data resets.
Here is my code:
function initialize(name, val) {
if(localStorage.getItem(name) === null) {
localStorage.setItem(name, val);
}
}
initialize("subCost", 0);
initialize("quantity", 0);
initialize("hasProduct", false);
Then since the storage only stores strings, I convert these into integers and boolean
var $quantity = parseInt(localStorage.quantity);
var $subCost = parseInt(localStorage.subCost);
var $hasProduct = localStorage.hasProduct == "true";
Before without the initialize function, I made the local storages items like this
localStorage.setItem("subCost", 0);
localStorage.setItem("quantity", 0);
localStorage.setItem("hasProduct", false);
and still converted these into those variable but they never saved with each refresh. How do I get these to save changes I make to them with each refresh.
The .setItem() method on localStorage doesn't only "sets" a "memory placeholder" for a value... It also overwrites it, if it already exist.
To save the user generated values, the best "moment" to save a "change" is the change event.
Use the same .setItem() method as in your initialize() function.
$("input").on("change",function(){
// Get id and value.
var id = $(this).attr("id");
var value = $(this).val();
// Save!
localStorage.setItem(id,value);
});
CodePen
Just as a hint...
This method to save values locally is ephemeral...
Values are kept until user closes the browser.
Not just closing the page, but closing the browser completely.
So to keep some values between pages navigated, this is the optimal use.
To store values for a longer run (like 6 months or longer), use cookies.
Have a look at jQuery Cookie plugin.

Saving and accessing API results in a variable in Chrome extension

I'm making a Chrome extension that pulls a large amount of data from an API and uses it to modify content on a page. Because the amount of data is so large, I'd like to be able to save it once in the browser and be able to access it instead of doing an API call each time a page loads.
It's my understanding this can be done by putting the API call in the background page and then calling the variable from the background page in the content script. I've also tried storing the data in local storage. Neither method is working for me and I don't understand what I'm doing wrong.
In my code in the background page, I have the API results stored in a variable. I'm calling it in the content script like this:
var background = chrome.extension.getBackgroundPage();
var myData = background.APIData; //where APIData is the variable I set in the background page
My attempt to use local storage looks like this:
//Background page
chrome.storage.sync.set({'value': APIData}, function() {
// Notify that we saved.
console.log('APIData saved to storage');
});
//Content script
var myData = localStorage["APIData"];
As of this moment, the extension isn't even loading in the page using the code where I'm trying to access local storage. The extension will load with the other method but the data doesn't seem to be there. I know my API call is working because the extension works when I put it all in the content script. But that creates the problem where I'm calling the API each time the page loads. Help please!
Examine your code closely. You are setting the data to two different bins.
First, you call chrome.storage.sync.set and set "value" to the value of APIData.
Second, you call localStorage['APIData'] which refers to a separate storage bin and property name.
Two solutions here, the first being the preferred way to set/get persistent data in a Chrome extension:
A1) set it with chrome.storage.sync.set( { value:data } )
A2) get it with chrome.storage.sync.get( null, function( storage ){ storage.value } )
B1) set it with localStorage.value = data
B2) get it with localStorage.value

Categories

Resources