I dive into Bjorn Staal's mind blowing experiment
You may’ve seen on Twitter that a guy created an amazing thing. Specifically, showing multiple things inside a browser based on how many browsers are opened. He was also so kind as to share his basic code on GitHub.
Now, I’m not a designer, so doing some interesting stuff is something I’ll leave to the people who are better at it. What I’m interested in is the coding behind it. And that’s what I’m going to break down in this part.
So, if we inspect the code, we can see basically 3 things happening:
So, let’s break it down a bit!
So, the key here is event listener. Specifically, window.addEventListener('storage')
.
In hindsight, it’s obvious that there’s an event listener for that. But I hadn’t considered that being a thing. So how exactly does it help us?
Well, this is a clever play now. Basically, what we do is:
One thing to note is that this is actually something that propagates only to other browsers, not the current one! You can try it yourself:
You can try that with the following code:
window.addEventListener("storage", (e) => {
console.log(e);
console.log("hit in storage");
});
const onClick = () => {
if (localStorage.getItem("hi")) {
localStorage.removeItem("hi");
} else {
localStorage.setItem("hi", "hello");
}
};