Cannot use localStorage - javascript

Why does local storage not work?
I have recently decided on a small website I am working on that I want to try having switchable themes. I want the themes to persist past the session and I am not at the point of logins yet, so I am looking in to local storage.
The console log here confirms the function is being run, but no storage is created for the page.
var main = function() {
$('#theme1').click (function () {
localStorage.setItem("theme", "1");
console.log("click");
});
}
$(document).ready(main);
I have also tried localStorage.theme = "1"; to no avail.
I am on the latest Chrome, but despite it being obvious that html 5 is supported I have checked on the w3 website w3schools.com/html5_webstorage and running the code through their "Try it Yourself" system works.

Please refer the image for check/verify the localstorage works or not. also u wrote code for click event... click that even and then see in console. one more thing in console log
var main = function() {
$('#theme1').click (function () {
localStorage.setItem("theme", "1");
console.log(localStorage.getItem('theme'));
});
}
$(document).ready(main);
vote if u like...

Reading local storage on loading the page has worked.
I used the developer window console to run localStorage.theme = "1" as per Dan Prince's comment, and it looked like it was not working for a simple reason. You have to leave the local storage view and go back in to see changes, it does not refresh.
How I was viewing the local storage initially is clicking the icon to the left of the address in the address bar which shows cookies, local storage and connection information. This does instantly update and persist with local storage set from w3schools.org but does not read the local storage from my page for some reason.

Related

Local Storage using Dexie not staying persistent

I am using Dexie to access IndexedDB on a flash card maker project. I can manipulate the database as expected, and it stays in the database if I close and reopen the browser, but often when I open up the project after not working on it for a few days, the stored data I put into the database isn't there any longer.
I did some research and discovered that I need to make the database persistent, but I can't figure out how to do that.
I have pretty much copied the recommended code from the Dexie Storage Manager page into the onLoad function for the main page, index.js. Here is the relevant code:
//When the page loads, display the decks in ul on the webpage.
window.addEventListener('load', onLoad);
async function onLoad() {
//Check how much data is available.
showEstimatedQuota();
//Make sure the storage is persistent.
isStoragePersisted().then(async isPersisted => {
if (isPersisted) {
console.log(":) Storage is successfully persisted.");
} else {
console.log(":( Storage is not persisted.");
console.log("Trying to persist..:");
if (await persist()) {
console.log(":) We successfully turned the storage to be persisted.");
} else {
console.log(":( Failed to make storage persisted");
}
}
});
}
The above onLoad function references three functions I have saved on dexie-setup.js:
//This function makes the storage persistent.
//(Copied from https://dexie.org/docs/StorageManager)
async function persist() {
return await navigator.storage && navigator.storage.persist &&
navigator.storage.persist();
}
//This function checks if the storage is persistent.
//(Copied from https://dexie.org/docs/StorageManager)
async function isStoragePersisted() {
return await navigator.storage && navigator.storage.persisted &&
navigator.storage.persisted();
}
//This function logs to console how much data is available.
//(Copied from https://dexie.org/docs/StorageManager)
async function showEstimatedQuota() {
if (navigator.storage && navigator.storage.estimate) {
const estimation = await navigator.storage.estimate();
console.log(`Quota: ${estimation.quota}`);
console.log(`Usage: ${estimation.usage}`);
} else {
console.error("StorageManager not found");
}
}
My console logs:
dexie-setup.js:56 Quota: 6358499328
dexie-setup.js:57 Usage: 25370
index.js:30 :( Storage is not persisted.
index.js:31 Trying to
persist..:
dexie-setup.js:84 Done checking dexie.
index.js:33 :) We successfully turned the storage to be persisted.
However, if I refresh the page, I get the same thing logged on my console: the database is still set to not persistent.
The showEstimatedQuota function checks the data storage and confirms that the DataStorage API is functioning, so I don't think that's the problem. (I'm only storing small objects with text in them, so I don't expect to exceed the storage limit, anyway.)
So far, the project is entirely local on my chromebook, and I am viewing it on a Chrome browser.
Please let me know how to make my database persistent. I'm pretty new to this (this is my first question on stackoverflow!), so hopefully it's an easy problem to solve! Thanks in advance.
citing the documentation of Dexie: "Even though IndexedDB is a fully functional client-side database for the web, it is not a persistent storage by default. IndexedDB without StorageManager is just a “best-effort” database that can be erased in situations of low disk space on a device. The browser may delete your database without notifying the user in case it needs to free up space for other website’s data that was used more recently than yours."
So, you can't make the database persistent. Just make a “best-effort”.
This links can be of help:
https://web.dev/persistent-storage/
Chrome.Storage.Local Persistence
I hope it will be of help to you.
The only way I have found is that if the user bookmarks the site then it enables persistent storage using the persist function:
//This function makes the storage persistent.
//(Copied from https://dexie.org/docs/StorageManager)
async function persist() {
return await navigator.storage && navigator.storage.persist &&
navigator.storage.persist();
}
So you may prompt the user to bookmark your site when it loads.

How to get and set values in Chrome storage?

I am learning JS these days and making a chrome extension. I want to store user data in chrome's storage API. And I want to ensure if the user has downloaded the extension for the first time then the variable should be 0 else change dynamically.
"use strict";
// chrome.storage.sync.clear()
chrome.storage.sync.get("totalviews",function(views){
if (views.totalviews){
console.log("There")
}
else{
console.log("Not there")
chrome.storage.sync.set({"totalviews":0})
console.log("Done!!")
}
})
However I am not able to update the variable to 0 if it does not exists. Any help?

chrome.storage seems to lose state after switching back-and-forth between tabs

Background
I am currently building a chrome extension collects cookies for the active tab and stores these in chrome.storage.local as a JSON string (popup.html) before being redirected to a different popup (cookie_popup.html). The stored cookies are then used to populate a table to display the contents. This works fine as long as I do not switch between browser tabs, I can open- and close the popup (cookie_popup.html) as often as I want while getting the desired effect.
The problem
When I navigate to another tab the table is no longer populated and chrome.storage.local just returns an empty object. chrome.storage.local seemed to have cleared but only for the stored cookies, not any of the other states that I have stored. I hope somebody can help me understand why.
What I have tried
I have tried changing chrome.storage.local to chrome.storage.sync, nothing changed. I also made sure that the cookies were not accidentally set again upon loading a new tab.
The code
The tabHandler that sets cookies in storage (popup.html - only called on button press).
chrome.tabs.query({active: true, currentWindow: true}, tabHandler);
function tabHandler(tabs) {
chrome.cookies.getAll({url: tabs[0].url}, function(cookies) {
chrome.storage.local.set({cookiejar: JSON.stringify(cookies)});
});
}
Populating the cookie table (cookie_popup.html).
chrome.storage.local.get('cookiejar', function(value) {
try {
let jar = JSON.parse(value.cookiejar);
// ... Snipped ...
} catch (e) {
console.error(e);
warningAlert.style = 'display: block;';
warningAlert.innerText = 'Could not parse cookies; Please restart process.';
}
});
Whenever opening a different tab and opening the extension popup the JSON parsing fails because value.cookiejar is an empty object.

How to know if user has completed all tasks?

I am making kind of an app using only HTML, JavaScript and CSS, with several little games for kids (like puzzles, order words, draw and paint...). I have the index page with links to the pages of each game, and once the game is over, it redirects directly to the index page, all in the same browser tab.
What I would like to know is if there is some way of knowing when the player has completed one game, so after that, the game would be locked, and once the player has completed all games, it would unlock a special prize or someting.
I have tried with local storage, but the problem is that once I've played one game, it will stay locked, because the local storage keeps in memory that I have played it, even if I close the browser. Is there any way of using local storage with it "losing its memory" once you close the browser? Or is there a more efficient way than local storage?
Any help would be much appreciated!
A good read for you : http://www.smashingmagazine.com/2010/10/11/local-storage-and-how-to-use-it/
Here is what you can do with regards to local storage :
When the page is loaded set up your local storage and set all games to incomplete
Create a store() and check() function to help you out and make things easier
function store(game, status){
localStorage.setItem(game, status);
}
function check(game){
return localStorage.getItem(game);
}
window.onload = function() {
store("puzzle1", false);
store("puzzle2", false);
store("puzzle3", false);
}
As the user completes the game you can alter the data inside the storage :
someEvent() {
store("puzzle1", true);
}
and then at the end of the game, or on your games starting page just run some checks :
//if puzzle1 is true
if(check("puzzle1")) {
//do Stuff
}
I believe that should work for you.
You can use the SessionStorage. By definition "it persists in the same tab", meaning that once the page is closed, the storage is lost.
Reference: https://code.google.com/p/sessionstorage/
as an example you can follow this i hope it helps you...
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) != "undefined") {
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
</html>
try to google sessionstorage for html, there are many examples..good luck!!

Session lost window.location.href

I'm trying to redirect the user to another page width:
window.location.href = "url here" //relative link
but when I do, it clears my sessvars.keyPageArray variable. Anyone know how to keep a session variable after a redirect?
This is the sessvars library that I am using:
http://www.thomasfrank.se/sessionvars.html
UPDATE: I used google chrome debugger and my script actually does work. For some crazy reason it only works if I'm monitoring it variable by variable but not when I simply run it normally without the debugger on? Why is that happening?
Just because you named a variable sessvars doesn't make it so. Use localStorage, sessionStorage or cookies depending on your need.
All javascript context is unloaded and lost when the browser navigates to another page.
Example using localStorage:
window.onbeforeunload = function() {
localStorage.setItem( "session", JSON.stringify( window.sessvars) );
};
window.onload = function() {
window.sessvars = JSON.parse( localStorage.getItem( "session") || "{}" );;
};
Sessions are on the server side.
Nothing to do with the browser.
JavaScript doesn't keep data after the page is closed, to open anoher page, or eaven on refresh.
Eventualy you can store data in cookie.
One important thing causing the problem is when in server /phptmp directory does not exist or does not have writing permissions.

Categories

Resources