HTML5 local storage not saving between page refreshes - javascript

I am using HTML5 local storage for the first time using FF5. I have the below javascript, it should save a string into local storage, however when the page is reloaded there isn't any values in local storage. What am I doing wrong? Why is 'foo' not populated on the pages sedond load?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js</script>
<script>
$(document).ready(function() {
if (!localStorage) {return false; }
var foo = localStorage.getItem("key1");
if (foo != null)
{
document.getByName("identifier").value = foo;
}
localStorage["key1"] = "value1";
});
</script>

You should use localStorage.setItem. For example
localStorage.setItem("key1", "value1");
NOTE: IE 7 does not have localStorage support

I've also had this same issue. I've discovered that I am unable to retrieve items from local storage during the document.ready, but I am able to get the items afterwards.

I believe you need to use the "setItem" method, i.e.:
localStorage.setItem('key1', 'value1');

Have a look at my code
You do not need getItem and setItem
jQuery('.close-intro').click(function() {
window.localStorage['intro'] = 1;
jQuery('.intro-holder').slideUp();
jQuery('.open-intro').show();
});
jQuery('.open-intro').click(function() {
window.localStorage['intro'] = 0;
jQuery('.intro-holder').slideDown();
jQuery(this).hide();
});
var opcl = window.localStorage['intro'];
if (opcl == 1) {
jQuery('.intro-holder').slideUp();
jQuery('.open-intro').show();
}
if (opcl == 0) {
jQuery('.intro-holder').slideDown();
jQuery('.open-intro').hide();
}

Related

Set cookies using js-cookies to array

newbie here regarding Javascript. I am following this thread to set cookies to array by clicking button. Product compare session. Its working but the problem is, when i reload or open new page, when i click the button on new page or refreshed page, the cookies doesn't add new value, it replace all cookies which has been set from previous page. Here is the script.
`
cookie_data_load = Cookies.get('compare_data');
$('.view__compare').attr("href", "https://shop.local/compare/?id=" + cookie_data_load);
var fieldArray = [];
$( ".product__actions-item--compare" ).click(function(){
fieldArray.push($(this).data("compare"));
var unique=fieldArray.filter(function(itm,i){
return i==fieldArray.indexOf(itm);
});
var str = unique.join('-');
Cookies.set('compare_data', str, { expires: 7, path: '/' });
cookie_data = Cookies.get('compare_data');
console.log(str);
console.log(unique);
alert(unique);
$('.view__compare').attr("href", "https://shop.local/compare/?id=" + cookie_data);
return false;
});
`
And second question is how to limit the number of cookies value (array) from above code? Many thanks
I have read the js-cookies github but cant understand single thing.
*** Updated code from https://stackoverflow.com/users/8422082/uladzimir
`
var fieldArray = (Cookies.get('compare_data') || '').split('-');
$(".product__actions-item--compare").click(function () { if
(fieldArray.length >= 3) {
alert("unfortunately limit exceeded :("); } else {
fieldArray.push($(this).data("compare"));
var unique = fieldArray.filter(function (itm, i) {
return i == fieldArray.indexOf(itm);
});
var str = unique.join('-');
Cookies.set("compare_data", str, { expires: 7, path: "/" });
cookie_data = Cookies.get("compare_data");
console.log(str);
console.log(unique);
alert(unique);
$(".view__compare").attr(
"href",
"https://shop.local/compare/?id=" + cookie_data
);
return false; } });
`
Ivan, whenever you reload a page, the array of data "fieldArray" is ALWAYS empty (despite there is data in "compare_data" cookie from previous browser session)
What you have to do is to initialize "fieldArray" with it's initial value taken from cookie:
var fieldArray = (Cookies.get('compare_data') || '').split('-')
Cookie stores string data with maximum size of 4kb. More over, cookie have no idea, if it stores serialized array, object, or anything else... It just keeps a string of text and that's it. So (as far as I know), there is no way to limit array length using cookie settings.
So, the only workaround here is to do this length-check programmatically, like following:
$('.product__actions-item--compare').click(function () {
if (fieldArray.length >= 3) {
alert('unfortunately limit exceeded :(');
} else {
// do your actions
}
});

How to display the value the local storage holds on the HTML page

I have 2 problems:
When I load the HTML page, and I look in the "Debug" in inspect it continuously says that the Local Storage is undefined
How to display the Local Storage value in the HTML page
JS code:
var loadLives = setInterval(showLives, 100);
// get lives from localstorage
var livesInStorage = window.localstorage.getItem('lives');
let lives;
if(livesInstorage) {
//parse localstorage data to Int
lives = parseInt(livesInstorage, 10);
}
else {
// initial value (in this case: 3)
lives = 3;
}
function loseLife() {
if (lives > 1) {
lives = --lives;
// set changed value in localStorage
window.localstorage.setItem('lives', lives);
}
else {
location.href='fail.html';
}
}
function showLives() {
document.getElementById("lifeamount").innerHTML = window.localstorage.getItem('lives');
}
From the code you shared I can see that you set the variable 'lives' to 3 as initial value, but you didn't set it in the Local Storage there.
You only set it in the Local Storage when you call 'loseLives', but I don't see a call to this function.
Also, you have a typo. You wrote localstorage instead of localStorage.

local storage cookies fall back

I have created a local storage function to save and then load the shopping cart from the cookies but when I try to access this page on another machine, it gives me error. how do I add a fall back to these functions so that if the code is viewed on a server or another machine locally it will work on there too and store new cookies basically.
ShoppingBasket.saveCart = function() {
localStorage.setItem("shoppingCartCookie", JSON.stringify(this.cart));
};
// function to load cart
ShoppingBasket.loadCart = function() {
this.cart = JSON.parse(localStorage.getItem("shoppingCartCookie"));
};
This is the code that causes the problem...
ShoppingBasket.addItemToCart = function(name, price, count) {
for (var i in this.cart) {
if (this.cart[i].name === name) {
this.cart[i].count += count;
this.saveCart();
return;
}
}
var item = new this.Item(name, price, count);
this.cart.push(item);
this.saveCart();
};
It causes the error message, Cannot read property 'push' of null
probebly your cart is null in localstorage
check if cart is null then sett to new array
ShoppingBasket.loadCart = function() {
this.cart = JSON.parse(localStorage.getItem("shoppingCartCookie")) || [];
};
You first need to check that the key is existing in local storage -
if ("shoppingCartCookie" in localStorage) {
//Your logic
}else{
//Your logic to create cookie
}
Local storage is machine specific, so for each macjine you first need to store the shoppingCartCookie, then only you will be able to access that.
Hope this will help you.

Parse, how to save Appended text

Let's say I have the following code:
$('.button').click(function() {
$('body').append("<p>Random Text</p>");
});
Where when the .button is clicked, text is appended to the body.
How would I go about saving that text and having it always appear when the user visits the page.
Would it be wise to store it in a variable and then send it to Data Browser under
POST or another Class?
Hope this isn't too confusing, thanks!
This isn't ideal but without creating a server side or clientside db this would be a quick fix. If the user switches browsers or clears their cache the storage is gone.
http://jsfiddle.net/4gseg96g/1/
$(document).ready(function() {
// Read localStorage.
function getStorage() {
var obj = localStorage.getItem('objName');
if(!obj) {
obj = '';
}
return obj;
}
// Append localStorage obj, if any.
$('body').append(getStorage());
$('.button').click(function() {
console.log('click');
var str = "<p>Random Text</p>";
$('body').append(str);
var d = getStorage();
d += str;
console.log(d);
localStorage.setItem('objName', d);
});
});

Check if localStorage is available

I know there has been many questions about checking for localStorage but what if someone manually shuts it off in their browser? Here's the code I'm using to check:
localStorage.setItem('mod', 'mod');
if (localStorage.getItem('mod') != null){
alert ('yes');
localStorage.removeItem('mod');
} else {
alert ('no');
}
Simple function and it works. But if I go into my Chrome settings and choose the option "Don't Save Data" (I don't remember exactly what it's called), when I try to run this function I get nothing but Uncaught Error: SecurityError: DOM Exception 18. So is there a way to check if the person has it turned off completely?
UPDATE: This is the second function I tried and I still get no response (alert).
try {
localStorage.setItem('name', 'Hello World!');
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!');
}
}
Use modernizr's approach:
function isLocalStorageAvailable(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
if(isLocalStorageAvailable()){
// available
}else{
// unavailable
}
It's not as concise as other methods but that's because it's designed to maximise compatibility.
The original source: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
Working example: http://jsfiddle.net/6sm54/2/
I'd check that localStorage is defined prior to any action that depends on it:
if (typeof localStorage !== 'undefined') {
var x = localStorage.getItem('mod');
} else {
// localStorage not defined
}
UPDATE:
If you need to validate that the feature is there and that it is also not turned off, you have to use a safer approach. To be perfectly safe:
if (typeof localStorage !== 'undefined') {
try {
localStorage.setItem('feature_test', 'yes');
if (localStorage.getItem('feature_test') === 'yes') {
localStorage.removeItem('feature_test');
// localStorage is enabled
} else {
// localStorage is disabled
}
} catch(e) {
// localStorage is disabled
}
} else {
// localStorage is not available
}
Feature-detecting local storage is tricky. You need to actually reach into it. The reason for this is that Safari has chosen to offer a functional localStorage object when in private mode, but with it's quotum set to zero. This means that although all simple feature detects will pass, any calls to localStorage.setItem will throw an exception.
Mozilla's Developer Network entry on the Web Storage API's has a dedicated section on feature detecting local storage. Here is the method recommended on that page:
function storageAvailable(type) {
try {
var storage = window[type],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return false;
}
}
And here is how you would use it:
if (storageAvailable('localStorage')) {
// Yippee! We can use localStorage awesomeness
}
else {
// Too bad, no localStorage for us
}
If you are using NPM, you can grab storage-available using
npm install -S storage-available
then use the function like so:
if (require('storage-available')('localStorage')) {
// Yippee! We can use localStorage awesomeness
}
Disclaimer: Both the documentation section on MDN and the NPM package were authored by me.
MDN updated the storage detect function. In 2018, it's more reliable:
function storageAvailable() {
try {
var storage = window['localStorage'],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage && storage.length !== 0;
}
}
Browsers that support localStorage will have a property on the window object named localStorage. However, for various reasons, just asserting that property exists may throw exceptions. If it does exist, that is still no guarantee that localStorage is actually available, as various browsers offer settings that disable localStorage. So a browser may support localStorage, but not make it available to the scripts on the page. One example of that is Safari, which in Private Browsing mode gives us an empty localStorage object with a quota of zero, effectively making it unusable. However, we might still get a legitimate QuotaExceededError, which only means that we've used up all available storage space, but storage is actually available. Our feature detect should take these scenarios into account.
See here for a brief history of feature-detecting localStorage.
With this function you can check if localstorage is available or not, and you keep under control the possible exceptions.
function isLocalStorageAvailable() {
try {
var valueToStore = 'test';
var mykey = 'key';
localStorage.setItem(mykey, valueToStore);
var recoveredValue = localStorage.getItem(mykey);
localStorage.removeItem(mykey);
return recoveredValue === valueToStore;
} catch(e) {
return false;
}
}
It is better to check availability of localStorage in conjunction with cookies, because if cookie is enabled the browser could detect that localStorage is available and type it as object, but provide no possibility to work with it. You use the next function to detect both localStorage and cookies:
const isLocalStorage = () => {
try {
if (typeof localStorage === 'object' && navigator.cookieEnabled) return true
else return false
} catch (e) {
return false
}
}
You can try this method
Anytime validate the content of the localstore
const name = localStorage.getItem('name');
if(name){
console.log('Exists');
}else
{
console.log('Not found');
}
I tried this solution in Chrome, Firefox and Edge and it worked correctly.
if (localStorage.getItem('itemName') === null )
{
// your code here ...
}
if the local variable on localStorage do not exist it will brind false.
You can create a checker function which tries to get a non existing item from the localStorage. When the localStorage is turned on you will normally get null returned. But when the localStorage is turned off an error will be thrown. You don't have to set any item for the checking.
const checkLocalStorage = () => {
try {
localStorage.getItem("x");
return true;
} catch {
return false;
}
}
Modifying Joe's answer to add a getter makes it easier to use. With the below you simply say: if(ls)...
Object.defineProperty(this, "ls", {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
});
Here is an easy check:
if(typeof localStorage === 'undefined'){
Use this to check localStorage is set or not. Its help you to get status of Localstorage.
if( window.localStorage.fullName !== undefined){
//action
}else{
}

Categories