I have been messing with localStorage and EventListener as seen below (from w3schools but with my messing around). The below always prints "A change was made in the storage area 3" to the div. I'm guessing this is the asynchronous nature of JS and I'd have to do something like promise chaining?
Secondly, and similarly, when I add removing the variable from localStorage and therefore, in EventListener, detecting that the variable is null, the below will not print anything to the div. i'm presuming it's seeing the removal before it can execute the first event (setting the variable) where it actually prints. Anyway, is there a way to pull off setting and removing a variable from localStorage or is this all that asynch stuff and needs promises (formerly callbacks and setTimeouts)? Thank you very much.
<button onclick="changeValue()">Change a Storage Item</button>
<p id="demo"></p>
<script>
window.addEventListener("storage", myFunction);
var x;
var c=0;
var mtv;
function myFunction(event) {
if (event.key==="mytime") {
mtv=localStorage.getItem("mytime");
if (mtv===null) {
} else {
document.getElementById("demo").innerHTML = "A change was made in the storage area "+ c;
}
}
}
function changeValue() {
x = window.open("", "myWindow", "width=200,height=100");
c=c+1
x.localStorage.setItem("mytime", "true");
c=c+1;
x.localStorage.removeItem("mytime");
c=c+1;
x.close();
}
</script>
</body>
</html>
UPDATE...I don't know how to format code in a response but instead of doing the above instant removal of the localStorage object, I went with an add/remove toggle on the localStorage variable...the adding or removal should trigger the ActionListener event in the grandparent window....
if(localStorage.getItem('mytime')){
x.localStorage.removeItem("mytime");
}else{
x.localStorage.setItem("mytime", "true");
}
Ok, the easier that you can do to see what happen is create an HTML with your code and open in your browser. Then, put breakpoints in the event and in the places in which you update the storage. Let's see:
If you need track your c values, you can save in the storage that values:
x.localStorage.setItem("mytime", c);
Then, you receive a first event with event.newValue="1" and a second one with event.newValue=null and event.oldValue="1".