I just want to check how the localStorage of a browser behaves over many tabs.
The idea of this small thing is to create a party for browser tabs. The first tab will create the party and every new tab can join the party. You can create a new tab with the button below.
Here the JavaScript code behind.
Here the code that checks for the storage and create it.
var storage = getLocalStorage();
function getLocalStorage() {
try {
var localStorage = window['localStorage'];
localStorage.setItem('test', 'test');
localStorage.removeItem('test');
return localStorage;
} catch(e) {
console.log(e.message);
}
}
Not that important for the behavior of the storage, but here the code that creates the random names.
var myName = getRandomName();
function getRandomName() {
var allowedChars = "abcdefghijklmnopqrstuvwxyz";
var randomName = "";
for (i = 0; i < 8; i++) {
var index = Math.min(Math.floor(Math.random() * allowedChars.length), allowedChars.length - 1);
randomName += String(allowedChars[index]);
}
return randomName;
}
Here the code for creating a party, joining a party, leaving the party and for checking of new party tabs and leaving party tabs.
console.log("Hello I am " + myName);
if (storage) {
// create a party if there is not party
var party = storage.getItem('party');
if (!party) {
party = [];
console.log("Let us open a party");
} else {
party = JSON.parse(party);
}
party.push(myName);
storage.setItem('party', JSON.stringify(party));
// leaf the party when closing the tab
window.onbeforeunload = function(e) {
var party = JSON.parse(storage.getItem('party'));
party.splice(party.indexOf(myName), 1);
if (!party.length) {
storage.removeItem('party');
} else {
storage.setItem('party', JSON.stringify(party));
}
return null;
};
// check for new or leaving party tabs
window.addEventListener('storage', function(e) {
if (e.url === window.location.href && e.key === "party") {
var oldParty = JSON.parse(e.oldValue);
var newParty = JSON.parse(e.newValue);
for (var i = 0; i < oldParty.length; i++) {
if (newParty.indexOf(oldParty[i]) === -1) {
console.log(oldParty[i] + " left the party");
break;
}
}
for (var i = 0; i < newParty.length; i++) {
if (oldParty.indexOf(newParty[i]) === -1) {
console.log(newParty[i] + " joined the party");
break;
}
}
}
});
}