I'm using a localStorage to store some stuff ( profile visits history ).
Every time profile is open, i get object, add more entries and update object.
This can lead to data loss (example: tab1:open, tab2:open, tab1:save, tab2:save).
Now, if I hold cntrl and open many new tabs at once, how to pervent data loss?
Didn't find anyhing about localStorage locking.
You can increment a variable instead of getting a whole new object, or push that new object into an array and calculate the total views getting the length of that array. The localStorage is shared across the different tabs as long as they are in the same domain.
Option 1.
Check and put a variable (e.g. editing) to localStorage when a tab is opened. So if another tab is open, you can create a warning on new tab. Clear that variable onPageUnload event. (Pessimistic Lock)
Option 2.
Update/put a variable (e.g. saveTime or saveCount) on save action. When a tab is opening, retrieve this variable and on save action check if the variable is remaning the same. If value is not the same, warn the user that he/she is editing an oldest version of the data. (Optimistic Lock)
Optimistic Lock vs Pessimistic Lock
Related
Obviously, we are able to store user data in sessionStorage.
Also, we can watch changes to sessionStorage:
window.addEventListener('storage', function(e) {
But what if we are also, for example, sending some info to our db and we need to do some important actions when user is done with our website, and he is closing all opened browser tabs of our website, and sessionStorage is about to die?
There is the event onbeforeunload, but it doesn't fit our issue, because many tabs of the same website can be open at once, and we cant be sure it is the last one.
So question is - can we detect when sessionStorage is about to die?
The goal is to detect when the last tab accessing a specific site is closing.
Assuming each tab is associated with a unique session ID, the following method should work:
Upon page load:
obtain session ID
retrieve array of active session IDs from localStorage
if session ID is not present in array, add it
store array to localStorage
Upon page unload:
retrieve array of active session IDs from localStorage
find and remove current session ID from array
update array to localStorage
if array is empty, perform your "last tab closing" action
What About Browser Crashes?
This scheme doesn't handle when a browser crashes. In that case, the page unload will never be detected, and localStorage will never have its array of active session IDs cleared.
One way to accommodate a crash is to set a timestamp with each session ID stored, then remove old session IDs.
let sessionArr = [
{ sessionId, timestamp },
...
]
I'm using TaffyDB to have a local/offline database
but unfortunately - after refreshing the browser tab - it loses the data
example:
I have this initial variable
var clist = TAFFY();
onclick event on button - it execute this statement
clist.insert({"123" , count:count , color:color , size:size});
after clicking it - and reload the browser tab , I execute this statement
alert(clist({PID : "123"}).count());//output 0
however the previous statement should output 1
but unfortunately - after refreshing the browser tab - it loses the data
Well, yeah, that's how TaffyDB works.
however the previous statement should output 1
No, it shouldn't.
TaffyDB is in-memory only. As soon as the context for your script is torn down, such as on a page reload, it's gone. If you want to persist it, you have to do that yourself.
The easiest thing to do is serialize the entire dataset as JSON and shove it in localstorage, provided it's small enough to fit there.
As per taffydb documentation, to persist data into localStorage, you can use db.store()
let db = TAFFY()
db.store('mydb')
This single function will both store the current data in-memory and retrieve previously stored data. So, if you call store at the beginning of your script, then on a window refresh, the stored data will be loaded.
BEWARE: However, the saving routine for db.store() is called as a non-blocking process... so if you wish to immediately retrieve data that you stored using some other call on localStorage, it will likely not be there. The best practice for store() is thus to call it on window load and then whenever you wish to save your existing data.
I want to dynamically load an image using jQuery like this:
main.js
var slidersrc=""; //try to define global variable - not sure if this is correct
jQuery(document).ready(function() {
jQuery("#sliderimg").attr('src', slidersrc);
});
jQuery("#selection1").click(function() {
slidersrc='wp-content/themes/*****/slide1.png';
});
So the first time user access my website, the slider is empty. After user clicks on one of the selection areas, I set the global variable value. Then if user continues to navigate at my website to different pages, the user should be shown a slider image as a result of his selection.
However, this doesn't appear to work.
Am I correctly using the global variable in jQuery? Or is there a better way to save the user selection value in client side?
thanks!
Global variables do NOT survive from one page to the next. Each page starts an entirely new javascript context (all new global variables, functions, etc...).
If you want to save state from one page to the next, your options are:
Put the data in a cookie which you can read from each successive page when that page loads.
Put the data in a browser local storage which you can read with javascript from each successive page when that page loads (recommended option).
Store the data on the server and embed it in each page as it is served from the server.
You can read about how to read and write from browser LocalStorage here and here.
If you're planning on changing the slider image each time the user clicks, then perhaps you want to save an index into an image array in local storage. When the page loads, you read the current index from localStorage (or supply a default value if no value exists in local storage), then write back the current value to localStorage for the next page. If the user takes some action that causes the index to update to a new value, then you update your page and then write that new index into localStorage so the next page can read it from there and so on.
LocalStorage is a similar concept to cookies, but it's a bit easier to manage and more efficient (the data is not sent to the server with every page request).
I have some pages, on the last page I need to know what choices a user made on the two last pages.
Like this:
a.html
User has three choices here that takes him/her to different urls. I need to somehow save this choice and use it later.
Example:
<script>globalVariable1="firstchoice"</script>
b.html
This is one of three choices page and here the User have 3-4 new choices that takes him/her to different urls. I also need to save this choice somehow for later use.
Example:
<script>globalVariable2="thirdchoice"</script>
c.html
This is the page where I need to know what choices the user has made earlier. To be able to link back to those exact pages if the user wants to go back in my breadcrumb-solution.
Example:
<script>
if(globalVariable1 == "firstchoice"){
//do this
}
if(globalVariable2 == "thirdchoice"){
//do this
}
</script>
Can I do this with some global variables in javascript or how can I solve this?
Thanks
You can use localStorage. A browser API that persists key/value pairs even if you navigate between pages, reload the page or close and reopen the browser.
//setting a value
localStorage["foo"] = "bar";
//getting a value
var x = localStorage["foo"];
Using sessionStorage will also work.
//setting a value
sessionStorage["foo"] = "bar";
//getting a value
var x = sessionStorage["foo"];
Wikipedias Web Storage article describes the difference between localStorage and sessionStorage as:
Data placed in local storage is per domain (it's available to all scripts from the domain that originally stored the data) and persists after the browser is closed. Session storage is per-page-per-window and is limited to the lifetime of the window. Session storage is intended to allow separate instances of the same web application to run in different windows without interfering with each other, a use case that's not well supported by cookies.
You will have to store cookies to track the user's state. Try cookie.js. It has a really simple key-value interface that you can read about on its GitHub page.
Web pages are stateless, so you cannot share global JavaScript variables between pages.
However you can set global variables for your page and containing modules by using the value of the cookie.
Your cookies will be available on all pages of your domain for the current browser.
Example:
//Page 1: Set cookie depending on user choice
$.cookie("choice1", ValueOfChoice1);
//Page 2: Get previous user choice
globalVariable1 = $.choice1("example");
You can read Setting cookies with jQuery if you want more details about how to use cookies.
you can use localStorage or sessionStorage.
Another choice if you're using some server-side language like PHP or Asp.Net is to sore those values in the user's session on the server.
I want to communicate between two different tabs in the same browser (on the same domain).
When a specific event fires in the second tab, I change a localstorage variable value (using Javascript). I want to detect this change on the first tab. The variable is named "status" and the value changes from 0 to 1
I was thinking for a possible solution and I think that using a timer on the first tab will work, but I think also that there must be a better way.
Do you know if there is any way to detect when the "status" variable value changes without using a timer?
Thanks a lot!
It seems that Storage events should provide what you need.
The HTML spec on storage events ( http://dev.w3.org/html5/webstorage/#the-storage-event )
says :
The storage event is fired when a storage area changes, as described
in the previous two sections (for session storage, for local storage).
When this happens, the user agent must queue a task to fire an event
with the name storage, which does not bubble and is not cancelable,
and which uses the StorageEvent interface, at each Window object whose
Document object has a Storage object that is affected.
Note the final clause, all windows which have access to the storage should be notified of any change.
However note the following clause in previous section of the spec :
When the setItem(), removeItem(), and clear() methods are called on a
Storage object x that is associated with a session storage area, if
the methods did something, then in every Document object whose Window
object's sessionStorage attribute's Storage object is associated with
the same storage area, other than x, a storage event must be fired, as
described below.
So the document which provoked the change is not alerted.
There is definitely a better way -- using events built into the localstorage mechanism. When you update localstorage in tab2, tab1 will get an update event which you can then use as a signal to read the new value from localstorage.
For more info, see:
Bug with Chrome's localStorage implementation?
http://diveintohtml5.info/storage.html