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!!
Related
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.
Complete - Edited Once
I am looking to create a Like Counter with persistent Memory!
Right now, my project is stored on a USB-Drive and I'm not thinking of uploading my semi-finished site to the Internet just yet. I'm carrying it around, plugging and working.
A feature of the site, is a Heart Counter and Like Counter, respective with their symbolic icons.
I have a little sideline JavaScript file that has a dozen functions to handle the click-events and such - such as the Number Count of the counters.
But, as the values of the counters are auto-assigned to Temporary Memory - if you were to reload the page - the counter number would reset to it's default, Zero. A huge headache...
Reading from .txt
I thought of using the experimental ReadFile() object to handle the problem - but I soon found that it needed a user-put file to operate (from my examinations).
Here's my attempt:
if (heartCount || likeCount >= 1) {
var reader = new FileReader();
var readerResults = reader.readAsText(heartsAndLikes.txt);
//return readerResults
alert(readerResults);
}
When loaded, the page runs through standard operations, except for the above.
This, in my opinion, would have been the ideal solution...
Reading from Cookies
Cookies now don't seem like an option as it resides on a per-computer basis.
They are stored on the computer's SSD, not in the JavaScript File... sad...
HTML5 Web Storage
Using the new Web Storage will be of big help, probably. But again, it is on a per-computer basis, no matter how beautiful the system is...
localStorage.heartCount = 0 //Originally...
function heartButtonClicked() {
if (localStorage.heartCount) {
localStorage.heartCount = Number(localStorage.heartCount) + 1
}
document.getElementById('heartCountDisplay').innerHTML = localStorage.heartCount
} //Function is tied to the heartCountButton directly via the 'onclick' method
However, I am questioning whether web storage can be carried over on a USB-Drive...
Summarised ideas
Currently, I am looking to Reading and Editing the files, as it's most ideal to my situation. But...
Which would you use? Would you introduce a new method of things?
Please, tell me about it! :)
if (typeof(Storage) !== "undefined") { //make sure local storage is available
if (!localStorage.heartCount) { //if heartCount is not set then set it to zero
localStorage.heartCount = 0;
}
} else {
alert('Local storage is not available');
}
function heartButtonClicked() {
if (localStorage.heartCount) { //if heartCount exists then increment it by one
localStorage.heartCount++;
}
//display the result
document.getElementById('heartCountDisplay').innerHTML = localStorage.heartCount
}
This will only work on a per computer basis and will not persist on your thumb drive. The only way I can think of to persist the data on your drive is to manually download a JSON or text file.
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.
i have this function:
<script language="javascript">
function live(){
var d = $live;
var elm = document.getElementById("live");
if(d==1){
elm.style.display = 'block';
} else{
elm.style.display = 'none';
}
}
</script>
setInterval(function(){live();},10000);
and im just concerned about my page getting stuck after having it open on the browser for a while or causing my users browser to stop responding or anything like that. How safe is to use loops like this?
Is this what google or facebook use to show new notifications alerts on their page in real time? That seems to go pretty smoothly.
Thank you.
This isn't a loop in the traditional sense, it's really just a function which is called at a regular interval, so you are in the clear here. Just be careful that nothing increases the memory use each time it executes, as that is what will most likely be what will kill the user's browser.
Also, the setInterval needs to me in a script tag, otherwise it will show up on your page.
Use of setInterval is a common practice for showing notifications on websites. It wont hang your page, although you must clear the interval once it is no longer required. Say you have already shown the notification, so better hold the reference of setInterval so that you could clear it later.
var ref = setInterval(fn, 100);
clearInterval(ref);
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.