JSFiddle - React, Tailwind, and code Playground
by tjcrowder
HTML
<div>
<label>
<input type="checkbox" id="chk-event" checked> Hook storage event
</label>
</div>
<div>
<label>
<input type="checkbox" id="chk-show" checked> Show value when event received
</label>
</div>
<div>
<input type="button" id="btn-run" value="Run">
</div>
JavaScript
function log(...msgs) {
console.log(new Date().toISOString().substring(11), ...msgs);
}
function setValue(value) {
localStorage.setItem("tab", value);
}
function getValue() {
return JSON.parse(localStorage.getItem("tab"));
}
if (console.clear) {
console.clear();
}
showValue("Value on load:");
document.getElementById("btn-run").addEventListener("click", function() {
this.disabled = true;
if (document.getElementById("chk-event").checked) {
log("Hooking event");
window.addEventListener("storage", function(e) {
if (document.getElementById("chk-show").checked) {
log("Got storage event with value", e.newValue, "local value is", getValue());
} else {
log("Got storage event with value", e.newValue);
}
});
} else {
log("Not hooking event");
}
let timeout = 10000 - (new Date().getTime() % 10000);
let tab = Math.random();
log(timeout / 1000, 's timeout, then writing:', tab);
setTimeout(function() {
setValue(tab);
const justAfter = JSON.parse(localStorage.getItem('tab'));
log(tab === justAfter ? "set correctly" : "GOT DIFFERENT VALUE", justAfter);
setTimeout(function() {
const got = getValue();
log(got);
if (got === tab) {
console.log('aquired lock');
} else {
console.log('did not aquire lock');
}
setTimeout(showValue, 500);
setTimeout(showValue, 1500);
setTimeout(showValue, 2500);
setTimeout(showValue, 3500);
}, 1000);
}, timeout);
});
function showValue(label) {
if (typeof label == "string") {
log(label, getValue());
} else {
log(getValue());
}
}