DEV Community

Cover image for Svelte and Localstorage remote
Domenik Reitzner
Domenik Reitzner

Posted on

Svelte and Localstorage remote

Idea 💡

localStorage is a very versatile part of web development for persisting data, but it can do so much more.

Every change fires a storage event on the window Object across tabs, which means it can be used as remote. 🤯

Potential uses 🛠

  • Video controller in a small popup window
  • Speaker view of presentation slides

Implementation ⚗

I used svelte-kit for the example (see links) 😉
The actual amount of code needed for this pattern is very minimalistic. On the remote side we only need to set a localStorage item and this in turn will trigger the event which we can listen to.

  on:click={() => localStorage.setItem('signal', 'message')}>
  Set 'message'
Enter fullscreen mode Exit fullscreen mode

The receiver is a little more work, but svelte is our friend and helper 💪

  let signal = '';
  const listener = () => {
    const value = localStorage.getItem('signal');
    if (!value) return;
    signal = value;
<svelte:window on:storage={listener} />

Received Signal: {signal}
Enter fullscreen mode Exit fullscreen mode

If you open the remote and the receiver (same browser and base URL) you should be able to send and receive signals across tabs without any network request.

⚠ because of security issues localStorage is blocked on the svelte REPL, so it will not work there

I hope you found this entry interesting and learned something new ☺

Links 🔗

Top comments (0)