DEV Community

Cover image for Sharing a state between windows without a server

Sharing a state between windows without a server

notachraf on December 23, 2023

Recently, there was a gif trending on social networks displaying an amazing piece of art made by Bjorn Staal. I wanted to recreate it, but lacki...
Collapse
 
framemuse profile image
Valery Zinchenko

You probably should use BroadcastChannel API for this purpose instead of ServiceWorker, not only because it serves the purpose better, but also in spite of perfomance.

Accordingly to this article, you may gain some performance by using BroadcastChannel if you send small amount of data per message:
hacks.mozilla.org/2015/07/how-fast...

This is my little research, I didn't test it, so let me know if I'm wrong.

Collapse
 
notachraf profile image
notachraf

Oh ! I didn't know about this API, thanks for sharing it !

tbh i didn't really care about the performance here , but that sounds clearly like a better tool for this ( as the SharedWorker only re-broadcast on each sync )
Thanks for the finding, i'll try it out !

Collapse
 
jorensm profile image
JorensM • Edited

I recently wrote about this topic also, but about sharing state between tabs instead of windows (but same concept). What I found is that BroadcastChannel is not sufficient for this, because there is no straightforward way to sync the state when the window is first opened.

Collapse
 
framemuse profile image
Valery Zinchenko

What straightforward means in this case?

Thread Thread
 
jorensm profile image
JorensM

Well think for a second for a way how you could possibly get initial state with BroadcastChannel. One way would be to have a 'get_state' message, upon which each channel responds with a 'set_state' message. But this would result in every single channel sending out a message, which is not optimal and could even be less performant than a shared worker. If it were possible to have communication between exclusively 2 channels then it would be different though.

Thread Thread
 
framemuse profile image
Valery Zinchenko

That's just one request at the time connection happens, comparing to the fact that 100 messages per second could be sent while moving windows around, this one time connection ping-pong is nothing.

You can also cache the state in a localStorage, so when any new connection appears, it can be simply read from it (though this will require using JSON.parse()).

So why do you think this is a problem? Maybe performance one, but setup load time is tolerable since users usually don't get mad when something loading for the first time.

Collapse
 
martoxdlol profile image
Martoxdlol

BroadcastChannels are really nice. I used it for sharing data across multiple tabs and it was great. Not only you can send small messages but complex objects with circular references and al lot of information really fast (much faster than serializing it to json and back).

Collapse
 
quangcuong0808 profile image
Tran Cuong

This is what I was looking for in the article. But the article also mentioned several ways to share state and they are interesting either.

Collapse
 
link2twenty profile image
Andrew Bone

Great article ☺️

Did you know when storage is updated by another tab it fires an event? Which will save you needing to poll.

Here is a version I made
github.com/Link2Twenty/spyglass

Here is the local storage hook I used (and wrote)
github.com/bloc-digital/uselocalst...

Collapse
 
crisz profile image
crisz

I've seen this in a Chrome Experiment something like 10 years ago, and since then I have been wondering how it was possible. This article explains everything, thank you

Collapse
 
notachraf profile image
notachraf

Oh, If you still have the link of the chrome experiment I'd be grateful ! But yeah I basically saw the gif from Bjorn and I was mesmerized !

If you found this article interesting, don't hesitate to share it with your friends/coworkers/community ! ( you can also subscribe to my newsletter notachraf.substack.com/ ! )

Collapse
 
crisz profile image
crisz • Edited

Now that I remember it was different, it was a ball running across windows.

Here is the link: experiments.withgoogle.com/browser...

The experiment is not launchable but there are videos, that's pretty cool!

Thread Thread
 
notachraf profile image
notachraf

ohhh that's fun, maybe i'll try recreating something like that ! thanks for sharing !

Thread Thread
 
crisz profile image
crisz

I think you can contact Mark Mahoney personally to have the source code. It was available a time ago

Collapse
 
michaeltharrington profile image
Michael Tharrington

Wow!!! This is so freaking cool. Appreciate you sharing.

I really like the bouncing ball experiment that @crisz brought up elsewhere in thread. I can imagine a lot of interesting ideas based on this concept...

For instance, I'd love to see some sort of a virtual ant farm with ants crawling between overlapped windows. Or maybe a program for making digital collages. What if one window was a magnifying glass that you could pull over another window?

I'm thinking there's gotta be some gaming potential here too.

You got my imagination running with this one! Very cool stuff. 😀

Collapse
 
notachraf profile image
notachraf

Thanks for the comment ! Happy to have sparkled some ideas ! I'd love to see what you do with this !

I actually imagined a game where one window is a maze, and the other window is a source of light, so you need to move one window to illuminate the maze and navigate it ( never had the time to actually finish it )

but yeah, feel free to share whatever you do with this ! ( and my source code is ofc open source, so if you need a starting block you can use it directly ! )

Collapse
 
framemuse profile image
Valery Zinchenko • Edited

If thinking about smoothness of actions, you probably should use requestAnimationFrame to long-poll localStorage for updates, this should give a user the best experience.

Collapse
 
notachraf profile image
notachraf

yeah you're absolutly right i think, I actually had a version using requestAnimationFrame, but I was worried it introduced too many concepts in the same article , but in more advanced projects ( like the one in 3D ) clearly the best thing to do is to schedule the polling in the next microTask ( and not a task like setTimeout )

Collapse
 
framemuse profile image
Valery Zinchenko

I don't think that's a problem for such articles, they are to demonstrate an approach and methods used to deal with problems.

Collapse
 
kosm profile image
Kos-M • Edited

you could incorporate this into a lib that enables this to work over the internet without using a server using p2p networks.
it needs a unique string to connect all nodes in same "room" then all nodes can exchange messages.So you can render position of all connected to the room nodes.
Overcoming the limitation of localhost only..

bugout

Collapse
 
notachraf profile image
notachraf • Edited

oh that's actually a really clever idea, I never deepdived onto the WebRTC API , I'll try it out and maybe write an article about it !

Collapse
 
axiol profile image
Arnaud Delante • Edited

I made a quick test to adapt your logic with the use of BroadcastChannel API here github.com/Axiol/linked-windows-br...

It's a first draft, lots of things can probably be improved, but it works

Collapse
 
notachraf profile image
notachraf

Damn that's impressive! Great work! It's way more compact, I think that's the most adapted way of doing it, do you mind if I edit the article to showcase and link to your work?

Collapse
 
axiol profile image
Arnaud Delante

Sure, no problem. I'll see if I have to time to clean everything a bit

Collapse
 
artxe2 profile image
Yeom suyun

It's quite fascinating.
I imagined sharing a single WebSocket or SSE connection across multiple windows using SharedWorker, but unfortunately, it's not supported in Android Chrome, which is disappointing.

Collapse
 
notachraf profile image
notachraf

Oh, that's a great application of SharedWorkers actually, a lot of companies put their caching logic inside of SharedWorkers

I didn't know it was not yet supported on Android, that's a bummer :(

btw if you don't want to miss anything, you can also subscribe for my newsletter, it's free : notachraf.substack.com/ !

Collapse
 
efpage profile image
Eckehard

Inspiring post, thank you!

I was wandering if there are any solutions to share state between multiple clients or even between client and server (which would need to distinguish multiple running sessions). Might be simple if you can accept a low timing, but what, if you want a fast response time?

Collapse
 
best_codes profile image
Best Codes

Awesome article! Very good an interesting content.

Collapse
 
notachraf profile image
notachraf

Thanks ! I'll be dropping more in the next coming weeks, if you don't to miss anything, you can also subscribe for my newsletter, it's free : notachraf.substack.com/ !

Collapse
 
best_codes profile image
Best Codes

Sure!

Collapse
 
kurealnum profile image
Oscar

This is super cool!

Collapse
 
slobodan4nista profile image
Slobi

I am not found of sharing my screen info with any website. How to disable this API?

Collapse
 
notachraf profile image
notachraf • Edited

Honestly, there is no easy way I think , but I have some ideas for you :

  • Either block completly javascript from executing
  • you can write your own javascript extension or some TamperMonkey script that will add a Proxy to window.screenX and window.screenY, and send wrong values to the website ( so they can't read it ) , if interested I could do a small article about it !

Edit : actually I just made an article to use proxies, if you want to read : dev.to/notachraf/create-your-own-i...

Collapse
 
proteusiq profile image
Prayson Wilfred Daniel

This is impassive. I saw the demo, and knowing how it was done is magical. Thank you.

Collapse
 
fidalmathew profile image
Fidal Mathew

Awesome article! Would be fun to try it out!!

Collapse
 
ayon_ssp profile image
AYON KARMAKAR

Awesome, a new level unlocked!

Collapse
 
ravavyr profile image
Ravavyr

cool proof of concept :)

Collapse
 
hosseinmirhosseini76 profile image
Hossein Mirhosseini

Good job 👏

Collapse
 
random_ti profile image
Random • Edited

Awesome content bro, really helpful 💖

Collapse
 
notachraf profile image
notachraf

Glad I could be of help !
I'll be dropping more in the next coming weeks, if you don't to miss anything, you can also subscribe for my newsletter, it's free : notachraf.substack.com/ !

Collapse
 
mpal15 profile image
mpal15

Good

Collapse
 
dsaga profile image
Dusan Petkovic

Very interesting article, if I were to do this I would dread having to do the math lol

Collapse
 
notachraf profile image
notachraf

hahaha, I messed up so much the signs on the base change, but a bit of try and retry makes it work !
Honestly I think that the ones making it in 3D have so much more complicated math 🤯

Collapse
 
kalinchernev profile image
Kalin Chernev

Cool 😎
Web never stops being fascinating 🚀

Collapse
 
obadajaras profile image
OBADA TAHAYNA

Great Article,thanks for sharing :)

Collapse
 
idledaydreamer profile image
Yehyun

wow good idea

Collapse
 
felixdev9 profile image
Felix

Holy Sh**!
This is awesome 😎. Really awesome work dude.

Collapse
 
notachraf profile image
notachraf

Thanks for the comment ! I'll be dropping more in the next coming weeks, if you don't to miss anything, you can also subscribe for my newsletter, it's free : notachraf.substack.com/ !

Collapse
 
thesanjeevsharma profile image
Sanjeev Sharma

When I saw the animation by Bjorn, I immediately thought of local storage.

Thanks for introducing a new concept of shared workers. Loved it!

Collapse
 
prettyalana profile image
Alana Edwards

Is there a way to do this with the Ruby programming language?

Collapse
 
notachraf profile image
notachraf

Sorry I don't know a lot of Ruby to do it ! But maybe with webassembly ?

Some comments have been hidden by the post's author - find out more